开发者

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('<','&lt;') + '<br>');
});
</script>

I expected to see:

&lt;p>Paragraph One&lt;/p><br>
&lt;p>Paragraph Two&lt;/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('<','&lt;') + '<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>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜