Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  194] [ 3]  / answers: 1 / hits: 6880  / 10 Years ago, sat, march 8, 2014, 12:00:00

I'm trying to get the HTML form of some objects(including text), using jquery contents. Here's what I got until now:



HTML



<div id=mydiv>
test
<p>foo</p>
<p>bar</p>
</div>


jQuery



$('#mydiv').contents().each(function(){
console.log($(this).html());
console.log($(this).prop(innerHTML));
console.log($(this).prop(outerHTML));
});


Is there any way to do this? I've searched around but I couldn't find anything.



Thank you in advance for the answer!


More From » jquery

 Answers
24

If you are looking for html including the wrapping element then



$('#mydiv').contents().each(function () {
//check if it is a text node
if (this.nodeType == 3) {
//if so get the node value for the element
console.log(this.nodeValue)
} else {
//if not use outerHTML or innerHTML based on need
console.log(this.outerHTML);
}
});


Demo: Fiddle


[#47048] Friday, March 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;