考虑以下 HTML:
<div>
aaaa
<span>bbbb</span>
cccc
<span>dddd</span>
eeee
</div>
我使用 JQuery 来匹配 [aaaa, cccc, eeee]
文本节点遵循 answers in this question :
$('div').contents().filter(function()
{
return this.nodeType === 3;
});
现在,我想用一个 HTML 元素替换每个文本节点 - 比如 <div>
包含文本节点。这是我想要的结果:
<div>
<div>aaaa</div>
<span>bbbb</span>
<div>cccc</div>
<span>dddd</span>
<div>eeee</div>
</div>
我尝试使用传递给 .each
的各种闭包.例如:
$('div').contents().filter(function()
{
return this.nodeType === 3;
}).each(function()
{
this.html("<div>" + this.text() + "</div>");
});
但是文本节点似乎没有提供任何.html
方法。 如何使用 JQuery 将文本节点替换为任意 HTML 元素?
最佳答案
this
指的是既不实现 html()
的普通 DOM 节点元素也不是 text()
方法。使用 $(this)
,您可以将元素制作成一个 jQuery 集合,以便能够访问 jQuery 方法。然后你可以使用replaceWith()
用 <div>
替换纯文本节点
$('div').contents().filter(function()
{
return this.nodeType === 3;
}).each(function()
{
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
aaaa
<span>bbbb</span>
cccc
<span>dddd</span>
eeee
</div>
关于javascript - 使用 JQuery 将文本节点转换为 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46977545/