可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
One way is to create your own wrapper:
$("#the_list_item").wrap('<div>').parent().html();
...do your thing, then unwrap:
$("#the_list_item").unwrap();
回答2:
I'm not sure if this works, but it might be worth a shot:
var html = $('#the_list_item')[0].outerHTML;
alert(html);
回答3:
Leaving just in case someone nowadays is still looking for this.
Full jQuery solution:
$('#the_list_item').prop('outerHTML');
回答4:
Here my solution, No jQuery required!
// Get a reference to the element by its ID.
var oEl = document.getElementById('the_list_item');
// Getting the outerHTML of an element:
var sOuterHTML = oEl.outerHTML;
alert( sOuterHTML );
Alternatively, it could be get the reference of element by means of jQuery, and then get the outerHTML.
var sOuterHTML = $('#the_list_item')[0].outerHTML;
alert( sOuterHTML );
// or
var sOuterHTML = $('#the_list_item').get(0).outerHTML;
alert( sOuterHTML );
回答5:
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
回答6:
Unfortunately, the outerHTML solution (accepted solution above) did not work for me on FireFox 9 / Windows 7 / JQuery 1.7 ...
Here is something that worked for me, according to Chetan Sastry (answer above):
var el = jQuery('#the_list_item').first();
var outerHtml = jQuery('<div>').append(el).html();
回答7:
Have you tried $("#the_list_item").parent().html()
?
回答8:
Here you can find a nice solution in the form of the code for a jQuery outerHtml plugin: http://yelotofu.com/2008/08/jquery-outerhtml/
回答9:
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();
回答10:
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.