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