jQuery在DOM元素中交换文本

jQuery在DOM元素中交换文本

本文介绍了使用子级JavaScript/jQuery在DOM元素中交换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个看起来像这样的DOM元素:

So I have a DOM element that looks like this:

<span>text</span>
<b>some more text</b>
even more text here
<div>maybe some text here</div>

我的问题是如何将 text 换成 candy 所以看起来像这样:

My question is how do I swap text for candyso it looks like this:

<span>text</span>
<b>some more text</b>
even more *candy* here
<div>maybe some text here</div>

我已经用正则表达式尝试过 .replace ,但是它会交换所有出现的文本.

I've tried a .replace with regex already but it swaps all the text occurrences.

我也不知道没有标签的文本在哪里.它可能在开头或结尾的中间(基本上在任何地方),我也不能删除子节点,因为我不知道它们的位置以及是否有< script> 子代,当我在所有文本操作的最后再次添加它时,它可能会重新运行.

Also I do not know where the text without tags will be. It could be in the middle at the beginning or at the end, (basically anywhere) I can't remove the child nodes either, because I don't know their positions and also if there is a <script> child it would probably rerun when I add it again at the end of all the text manipulation.

有人能指出我正确的方向吗?

Can anyone point me in the right direction?

推荐答案

您可以检查节点的 nodeType 属性:

You can check the nodeType property of the nodes:

$('#parent').contents().each(function() {
   if (this.nodeType === 3) {
      this.nodeValue = this.nodeValue.replace('text', 'candy');
   }
});

如果要用HTML替换文本,可以使用 replaceWith 方法:

If you want to replace the text with HTML, you can use the replaceWith method:

$('#parent').contents().filter(function() {
   return this.nodeType === 3 && this.nodeValue.indexOf('text') > -1;
}).replaceWith(function() {
    return this.nodeValue.replace(/(text)/g, '<strong>candy</strong>');
});

这篇关于使用子级JavaScript/jQuery在DOM元素中交换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 17:03