jQuery: Get HTML including the selector?

僤鯓⒐⒋嵵緔 提交于 2019-12-17 23:33:27

问题


Say I have this HTML:

<ul>
  <li id="example"><strong>Awesome</strong> example text</li>
</ul>

I want to be able to do something like $('#example').html() but right now doing that obviously only gets <strong>Awesome</strong> example text.

So how can I get the HTML including the selected element?

ie. <li id="example"><strong>Awesome</strong> example text</li>

I'm using jQuery 1.4.4.


回答1:


In this specific case:

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

See this page for more details.

And the discussion here: http://api.jquery.com/html/ (this explains that this isn't in jQuery core and why some logical solutions won't work)




回答2:


You could try this:

var html = $('<div>').append($('#example').clone()).html();



回答3:


For browsers that support it, outerHTML can do that. There are jQuery plugins like this and this that enable support via some clever jQuery.




回答4:


var outerHtml = $('#example').detach();



回答5:


Anything wrong with simply using $('#example') ? This grabs the whole thing!



来源:https://stackoverflow.com/questions/5587844/jquery-get-html-including-the-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!