如何使用jQuery获取innerHtml,包括标签?

Rak*_*yal 9 html javascript jquery dom

对不起,如果标题过于模糊; D.

实际上问题是,让我说我是这个代码.

<span id="spanIDxx" style="blah-blah">
   <tag1>code here </tag2> sample text 
   <tag2>code here </tag2> html aass hhddll
   sample text
</span>
Run Code Online (Sandbox Code Playgroud)

现在,如果我将使用代码.

jQuery("#spanIDxx").html();
Run Code Online (Sandbox Code Playgroud)

然后它将只返回innerHTML, <span id="spanIDxx" style="blah-blah">
但我想要一些可以返回包含指定元素的innerHTML的东西.

use*_*716 11

这将创建一个新的div并附加元素的克隆div.新的div永远不会插入到DOM中,因此它不会影响您的页面.

var theResult = $('<div />').append($("#spanIDxx").clone()).html();

alert( theResult );
Run Code Online (Sandbox Code Playgroud)

如果你需要经常使用它,并且不想再添加另一个插件,只需将它变成一个函数:

function htmlInclusive(elem) { return $('<div />').append($(elem).clone()).html(); }

alert( htmlInclusive("#spanIDxx") );
Run Code Online (Sandbox Code Playgroud)

或者自己扩展jQuery:

$.fn.htmlInclusive = function() { return $('<div />').append($(this).clone()).html(); }

alert( $("#spanIDxx").htmlInclusive() );
Run Code Online (Sandbox Code Playgroud)