Examining the DOM elements returned in a jQuery object
I have:
<p>Paragraph One</p>
<p>Paragraph Two</p>
<s开发者_StackOverflow中文版cript src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<script>
var x = $('p');
x.each(function(index) {
$('body').append($(this).html().replace('<','<') + '<br>');
});
</script>
I expected to see:
<p>Paragraph One</p><br>
<p>Paragraph Two</p><br>
But instead, the p tag itself is missing.
I'm trying to make my output look like console.log, which would identity x as two (2) paragraph elements.
It's getting the html within the paragraph, but console.log shows it AS a paragraph. So I guess I need to go up a level and then back down again?
This is because $(this).html()
will only give you the content of the <p>
element, not element itself.
Do this:
var x = $('p');
x.each(function(index) {
var p_html = this.outerHTML || $('<div>').append($(this).clone()).html();
$('body').append(p_html.replace('<','<') + '<br>');
});
This takes each <p>
element, and gets its .outerHTML
property (which is like innerHTML
but includes the owner's tag as well).
If the .outerHTML
property isn't supported (I'm looking at you Firefox!) then it uses the clone()
[docs] method to make a clone of the <p>
, adds it to a new <div>
and gets the .html()
of the <div>
.
精彩评论