jQuery: Get HTML including the selector?

2019-01-22 17:35发布

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.

5条回答
放我归山
2楼-- · 2019-01-22 17:52

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

查看更多
虎瘦雄心在
3楼-- · 2019-01-22 18:00

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楼-- · 2019-01-22 18:04

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)

查看更多
smile是对你的礼貌
5楼-- · 2019-01-22 18:07
var outerHtml = $('#example').detach();
查看更多
▲ chillily
6楼-- · 2019-01-22 18:14

You could try this:

var html = $('<div>').append($('#example').clone()).html();
查看更多
登录 后发表回答