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

3

考虑以下HTML代码:

<div>
    aaaa
    <span>bbbb</span>
    cccc
    <span>dddd</span>
    eeee
</div>

我使用JQuery按照这个问题的答案,匹配[aaaa, cccc, eeee]文本节点:

$('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元素?


为什么不在标记中修复它,而是在事后用JavaScript来“修补”它呢?也许可以看一下replaceWith方法。 - Taplar
这是一个重复的问题,链接为https://dev59.com/wm435IYBdhLWcg3wpx2x - Daniel Diekmeier
使用 $(this).html() - Dalin Huang
1
可能是 jQuery 选择和包装 textNode 的重复问题。 - Daniel Diekmeier
@Taplar:我无法控制标记。 - Vittorio Romeo
2个回答

4

this 指的是一个普通的 DOM 节点元素,它既没有实现 html() 方法,也没有实现 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>


1

您还可以使用jquery中的wrap将内容包装在div中。

.wrap()

描述:在匹配元素集合中的每个元素周围包装一个HTML结构。

REF: http://api.jquery.com/wrap/

$('div').contents().filter(function()
{
    return this.nodeType === 3;
}).each(function()
{
    $(this).wrap('<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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接