I have:
<p>Paragraph One</p>
<p>Paragraph Two</p>
<script 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:
This takes each
<p>element, and gets its.outerHTMLproperty (which is likeinnerHTMLbut includes the owner’s tag as well).If the
.outerHTMLproperty isn’t supported (I’m looking at you Firefox!) then it uses theclone()[docs] method to make a clone of the<p>, adds it to a new<div>and gets the.html()of the<div>.