gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:50:01 27 4
gpt4 key购买 nike

我正在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com