full HTML of object returned by jQuery selector

2020-02-10 12:56发布

given this html:

<li id="the_list_item"><img src="some_img"></li>

and this selectior:

$("#the_list_item")

I want to get the full html from the object return by the jQuery selector.

Using:

$("#the_list_item").html()

...just gives me the inner html (the <img src="some_img"> part)

But since:

$("#the_list_item").attr("id")

gives me 'the_list_item', this indicated that the whole list item is indeed included in the object returned.. so how do I get the full code from that object?

I want to get a String: <li id="the_list_item"><img src="some_img"></li> from my object, but can't find the way to do it.

10条回答
ゆ 、 Hurt°
2楼-- · 2020-02-10 13:45

Creating a new div DOM object and appending a clone of the div, then get the contents of wrapped div and finally removing the created DOM object.

var html = $('<div>').append($('#the_list_item').clone()).remove().html();
查看更多
smile是对你的礼貌
3楼-- · 2020-02-10 13:48

Leaving just in case someone nowadays is still looking for this.
Full jQuery solution:

$('#the_list_item').prop('outerHTML');
查看更多
爷、活的狠高调
4楼-- · 2020-02-10 13:48

There's no "outer html" equivalent in jQuery, but this might help: http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html

查看更多
The star\"
5楼-- · 2020-02-10 13:50

There are plugins for that. Just google for "jQuery outerhtml". The idea behind most of them is to clone the element, append it to an empty div and get that div's html.

查看更多
登录 后发表回答