最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the innerHtml, including the tag, using jQuery? - Stack Overflow

programmeradmin9浏览0评论

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 innerHTML including the specified element.

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 innerHTML including the specified element.

Share Improve this question edited Feb 1, 2015 at 16:27 Deduplicator 45.7k7 gold badges72 silver badges123 bronze badges asked Feb 23, 2010 at 15:16 Rakesh JuyalRakesh Juyal 36.8k73 gold badges178 silver badges216 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

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)

  1. 暂无评论