javascript - jQuery.contents() 获取每个元素作为 HTML/STRING

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

有什么办法吗?我四处搜寻,但找不到任何东西。

预先感谢您的回答!

最佳答案

如果您正在寻找包含包装元素的 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

关于javascript - jQuery.contents() 获取每个元素作为 HTML/STRING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22268540/

相关文章:

javascript - Jquery 删除按钮上的所有克隆单击

javascript - 将 json 放入模态

javascript - ReactJS - 目标随机元素

javascript - 如何在按下键时显示元素,然后如果再次按下,隐藏元素?

javascript - jQuery 每个函数在 ajax 调用后不起作用

jQuery每个方法没有返回值

javascript - 如何退出 mootools each()

javascript - 如何在 Ajax 中实现相同的行为

javascript - 当通过 javascript/jquery 更改值时,多个选择不会更新

javascript - 添加文章标签时将页脚固定在底部