javascript - 使用 JQuery 将文本节点转换为 HTML 元素

标签 javascript jquery html

考虑以下 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/

相关文章:

javascript 在嵌套函数中将项目添加到全局数组,更改不会反射(reflect)在使用 gmail api 的外部

javascript - Accordion 式 list 计数器 document.form[]

javascript - php脚本echo显示在控制台而不是文本输入中

javascript - 如何通过 jQuery 将 CSS 添加到类中?

html - 标题标签在 IE 中不显示

javascript - Bootstrap 悬停选项卡显示多个选项卡

javascript - CSS制作:active toggled

html - 垂直对齐在 td 内部不起作用

html - 浏览器,上传大文件

javascript - 使用Javascript禁用chrome中的保存密码气泡