Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.contents() get each element as HTML / STRING

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!

like image 714
Grozav Alex Ioan Avatar asked Mar 08 '14 11:03

Grozav Alex Ioan


1 Answers

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

like image 86
Arun P Johny Avatar answered Nov 02 '22 23:11

Arun P Johny