开发者

How to get the innerHtml, including the tag, using jQuery?

Sorry, if the title is too obscure ;D.

Actually the problem is, lets say i am this code.

<span id="spanIDxx" style="blah-blah">
   <tag1>code here </tag2> sample text 
   <tag2>code here </tag2> html aass hhddll
   sample text
</span>

Now if i will use the code.

jQuery("#spanIDxx").html();

then it will return just the innerHTML excluding <span id="spanIDxx" style="blah-blah">

but i want something which can return the i开发者_如何学编程nnerHTML including the specified element.


This will create a new div and append a clone of your element to that div. The new div never gets inserted into the DOM, so it doesn't affect your page.

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

alert( theResult );

If you need to use this frequently, and don't want to bother with adding yet another plugin, just make it into a function:

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

alert( htmlInclusive("#spanIDxx") );

Or extend jQuery yourself:

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

alert( $("#spanIDxx").htmlInclusive() );


You can copy the node to a new empty node, ask for new .parent() and then its .html()


Clone might be useful to you. I don't believe you actually need to do anything with the clone/s.


Haven't used this myself but looks like it may be of use:

http://yelotofu.com/2008/08/jquery-outerhtml/

demo here: http://yelotofu.com/labs/jquery/snippets/outerhtml/demo.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜