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

时间:2014-03-08 11:15:15

标签: javascript jquery each

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

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"));
});

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

提前感谢您的回答!

2 个答案:

答案 0 :(得分: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);
    }
});

演示:Fiddle

答案 1 :(得分:0)

尝试$('div')。html() - 它输出元素的html 或者console.log($('div')。html())

相关问题