使用jQuery仅替换div内的文本

131
我有一个像这样的 div:
<div id="one">
       <div class="first"></div>
       "Hi I am text"
       <div class="second"></div>
       <div class="third"></div>
</div>

我正在尝试使用jquery仅更改“ Hi I am text”文本为“ Hi I am replace”。 这可能很容易,但我无法做到。

使用 $('#one').text('')仅会清空整个#One div。


可能制作一个fiddle会很有帮助。 - Inkbug
1
使用$('#one').find('.first').text('Hi I am replace');代替$('#one').text(); 或者你可以直接访问元素并使用$('.first').text('Hi I am replace');替换文本。 - Kartik Chauhan
8个回答

154

文本不应该独立存在,应该放到 span 元素中。

修改为以下内容:

<span>Text</span>

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
</div>
$('#one span').text('Hi I am replace');

72
这不回答提问者的问题,他没有说他控制HTML。 - tar
1
这个已经工作了,但如何确保它被执行或不被执行?如果空白或标签更改,我能否运行异常?在绑定不成功的情况下,因为这个div是由代码从REST或数据库创建的。 - saber tabatabaee yazdi
这是错误的。.text 会将文本添加到现有的文本后面。 - sam kh

150

查找文本节点 (nodeType==3) 并替换 textContent:

$('#one').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});

请注意,根据文档,您可以将上面的硬编码3替换为Node.TEXT_NODE,这样更清楚您在做什么。

$('#one').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
       <div class="first"></div>
       "Hi I am text"
       <div class="second"></div>
       <div class="third"></div>
</div>


9
这应该是被采纳的答案,因为它不需要你改变HTML! - Wouter Rutgers
2
@Jamiec FWIW,我喜欢这个答案,因为它允许替换而不必担心破坏标记/脚本等。 - sehe
3
这对我非常有效。有时我们在无法更改HTML的情况下工作(例如SharePoint)。谢谢。 - Mark P.
1
@Paul 谢谢,现在更清晰了,我已经将其作为注释添加到这个旧答案中。 - Jamiec
你好,使用我的示例 https://jsfiddle.net/xpcf49mh/ 对我来说不起作用。 - Lenin Zapata
显示剩余2条评论

20

你需要将文本设置为除空字符串以外的其他内容。此外,.html()函数应该在保留 div 元素的 HTML 结构的同时完成这项工作。

$('#one').html($('#one').html().replace('text','replace'));

虽然这种方法在这种情况下可以工作,但我不喜欢这个选项,因为如果你用单词“second”替换单词“first”,或者只是将“i”替换为空格,它会破坏你的标签。 - JSON

11

如果您知道要替换的文本,可以使用以下方法:

$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';

http://jsfiddle.net/5rWwh/

或者

$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';
< p >$('#one').contents(':not(*)')选择在这种情况下非元素子节点,即文本节点,第二个节点是我们想要替换的节点。

http://jsfiddle.net/5rWwh/1/


2
jQuery 1.8.3开始,$('#one').contents(':not(*)')将不会选中任何内容。 - BruceHill

1

如果您无法更改HTML,可以使用这种非常原始但简短有效的方法。(它会清空父div,因此子div将被删除)

$('#one').text('Hi I am replace');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="one">
  <div class="first"></div>
  "Hi I am text"
  <div class="second"></div>
  <div class="third"></div>
</div>


2
这将删除 #one 的所有子 div。 - Scot Nery
1
@ScotNery 谢谢,我已经更新了答案。(虽然它在技术上回答了这个特定的问题)我假设除了用一个带有id的标签包装文本之外,这将是非常具有挑战性的。唯一的其他事情就是匹配要替换的字符串,但它真的很脆弱。 - ReturnTable

0

我曾经遇到过同样的问题,但是文本是父元素内的第一个节点。在这种情况下,您可以像这样做,而且非常快:

// find the children elements
 termsChildren = $('#one').children()

// replace the text, then re-append the children element.
 $('#one').text(' "Hi I am replace" ').append(termsChildren)

否则,您必须指定哪些子元素在文本之前,哪些在文本之后:

// find the children elements
 termsChildren = $('#one').children()

// remove all the content
 $('#one').text(' ')
// append the first child element
 $('#one').append(termsChildren[0])
// add the new text and then the other children
 $('#one').text(' "Hi I am replace" ').append(termsChildren.slice(1))


0
另一种方法是保留该元素,更改文本,然后将该元素附加回去。
const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

-1
当您使用jQuery替换元素的纯文本时,不能将纯文本单独放置,否则它将清除和/或替换整个元素。您应该将所有纯文本放在一个<span>元素内:

$(document).ready(function() {
  $("#change-btn").click(function() {
    $("#one").children("span").text("Hi I am replace");
  });
});
<!-- Import CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Import JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

<div class="m-2">
  <div id="one">
    <div class="first"></div>
    <span>Hi I am text</span>
    <div class="second"></div>
    <div class="third"></div>
  </div>
  <button type="button" class="btn btn-primary btn-sm mt-2" id="change-btn">Click to change text</button>
</div>


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