如何替换HTML标签中的文本?

3

我不知道如何称呼它,但我称之为半内部文本。

例子

<div id='myDiv'>
    This is the semi-inner text
    <div id='other'></div>
    This is the semi-inner text
<div>

我想使用jquery删除/替换那些这是半内部文本
我该怎么做?

使用JS将以下编程相关内容从英语翻译成中文。将其包装在<span class =“semiTxt”> </ span>中,并替换其中的文本 - Bongs
你应该使用span、div、p或其他元素将其包裹起来。如果一些文本没有被包裹起来,它就不是一个有效的网页。 - benck
6个回答

3
如果你只关心子节点...
$('#myDiv').contents().filter(function() {
    return this.nodeType == 3
}).each(function() {
    this.data = this.data.replace(/This is the semi-inner text/g, 'swapped');
});​

jsFiddle

如果您想检查所有后代节点,请在检测到元素节点(this.nodeType == 1)时使函数进行递归。


2
$('#myDiv')
    .contents()
    .filter(function() {
        return this.nodeType == 3;
    })
    .each(function() {
        $(this).remove();
    });

1
使用contents()函数并过滤掉所有节点类型等于3的节点,然后将它们移除:
$('#myDiv').contents().filter(function() {
    return this.nodeType == 3;
}).remove();

0
使用以下代码替换内容:
$("#other").html("your code");

并且用户将您的代码包装在带有ID的span标签中


0
最简单的方法是将它放在一个带有id的span标签中,例如:
<div id='myDiv'>
    <span id="myInnerText">This is the semi-inner text</span>
    <div id='other'></div>
    This is the semi-inner text
<div>

然后像这样替换它:

$("#myInnerText").text("replacement text");

0

你也可以像这样做:

target_div = $("#myDiv")
  reg_exp  = /This is the semi-inner text/g;
  new_text = "some other text"

  target_div.html(
    target_div.html()
      .replace(
        new RegExp(reg_exp),
        new_text)
        );
 });

演示


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