如何在不更改元素的子元素的情况下更改元素的文本?

新手上路,请多包涵

我想动态更新元素的文本:

 <div>
   **text to change**
   <someChild>
       text that should not change
   </someChild>
   <someChild>
       text that should not change
   </someChild>
</div>

我是 jQuery 的新手,所以这个任务对我来说似乎很有挑战性。有人可以指出我要使用的功能/选择器吗?

如果可能的话,我想在不为需要更改的文本添加新容器的情况下执行此操作。

原文由 ika 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 386
2 个回答

Mark 使用 jQuery 找到了更好的解决方案,但您也可以在常规 JavaScript 中执行此操作。

在 Javascript 中, childNodes 属性为您提供元素的所有子节点,包括文本节点。

因此,如果您知道要更改的文本始终是元素中的第一件事,那么给定以下 HTML:

 <div id="your_div">
   **text to change**
   <p>
       text that should not change
   </p>
   <p>
       text that should not change
   </p>
</div>

你可以这样做:

 var your_div = document.getElementById('your_div');

var text_to_change = your_div.childNodes[0];

text_to_change.nodeValue = 'new text';

当然,您仍然可以使用 jQuery 来首先选择 <div> (即 var your_div = $('your_div').get(0); )。

原文由 Paul D. Waite 发布,翻译遵循 CC BY-SA 3.0 许可协议

2018 年更新

由于这是一个非常受欢迎的答案,我决定通过将文本节点选择器作为插件添加到 jQuery 来对其进行更新和美化。

在下面的代码片段中,您可以看到我定义了一个新的 jQuery 函数,它获取所有(且仅)文本节点。您也可以将此函数与例如 first() 函数链接起来。我对文本节点进行了修剪,并在修剪后检查它是否不为空,因为空格、制表符、换行符等也被识别为文本节点。如果您也需要这些节点,那么只需将其从 jQuery 函数的 if 语句中删除即可。

我添加了一个示例,说明如何替换第一个文本节点以及如何替换所有文本节点。

这种方法使代码更容易阅读,并且更容易多次使用它并用于不同的目的。

如果您愿意, 2017 年更新 (adrach) 应该仍然有效。

作为 jQuery 扩展

 //Add a jQuery extension so it can be used on any jQuery object
jQuery.fn.textNodes = function() {
  return this.contents().filter(function() {
    return (this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== "");
  });
}

//Use the jQuery extension
$(document).ready(function(){
  $('#replaceAll').on('click', () => {
    $('#testSubject').textNodes().replaceWith('Replaced');
  });

  $('#replaceFirst').on('click', () => {
    $('#testSubject').textNodes().first().replaceWith('Replaced First');
  });
});
 p {
  margin: 0px;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
   **text to change**
   <p>text that should not change</p>
   <p>text that should not change</p>
   **also text to change**
   <p>text that should not change</p>
   <p>text that should not change</p>
   **last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>

等效于 Javascript (ES)

 //Add a new function to the HTMLElement object so it can be used on any HTMLElement
HTMLElement.prototype.textNodes = function() {
  return [...this.childNodes].filter((node) => {
    return (node.nodeType === Node.TEXT_NODE && node.nodeValue.trim() !== "");
  });
}

//Use the new HTMLElement function
document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('#replaceAll').addEventListener('click', () => {
    document.querySelector('#testSubject').textNodes().forEach((node) => {
      node.textContent = 'Replaced';
    });
  });

  document.querySelector('#replaceFirst').addEventListener('click', function() {
    document.querySelector('#testSubject').textNodes()[0].textContent = 'Replaced First';
  });
});
 p {
  margin: 0px;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
  **text to change**
  <p>text that should not change</p>
  <p>text that should not change</p>
  **also text to change**
  <p>text that should not change</p>
  <p>text that should not change</p>
  **last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>

2017 年更新(adrach):

自发布以来,似乎有几件事发生了变化。这是一个更新版本

$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");


原始答案(不适用于当前版本)

 $("div").contents().filter(function(){ return this.nodeType == 3; })
.filter(':first').text("change text");

来源: http ://api.jquery.com/contents/

原文由 Mark Baijens 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题