jQuery.contents()将每个元素都作为HTML/STRING

Gro*_*oan 5 javascript each jquery

我正在尝试使用jquery内容获取某些对象(包括文本)的HTML表单.这是我到现在所得到的:

HTML

<div id="mydiv">
    test
    <p>foo</p>
    <p>bar</p>
</div>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('#mydiv').contents().each(function(){
    console.log($(this).html());
    console.log($(this).prop("innerHTML"));
    console.log($(this).prop("outerHTML"));
});
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?我四处寻找,但找不到任何东西.

提前谢谢您的回答!

Aru*_*hny 12

如果您正在寻找包含包装元素的html

$('#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);
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴