5

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!

0

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try $('div').html() -- it's output html of element. Or console.log($('div').html())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.