How can I change an element#39;s text without changing its child elements?(如何在不更改子元素的情况下更改元素的文本?)
问题描述
我想动态更新元素的文本:
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);
).
这篇关于如何在不更改子元素的情况下更改元素的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不更改子元素的情况下更改元素的文本?


- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01