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

2022-01-30 00:00:00 jquery javascript html

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

I'd like to update element's text dynamically:

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

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

I'm new to jQuery, so this task seems to be quite challenging for me. Could someone point me to a function/selector to use?

如果可能的话,我想在不为我需要更改的文本添加新容器的情况下这样做.

If it is possible, I'd like to do it without adding a new container for the text I need to change.

推荐答案

Mark 使用 jQuery 获得了更好的解决方案,但您也可以在常规 JavaScript 中做到这一点.

Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.

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

In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.

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

So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this 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);).

Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).

相关文章