如何在不更改其子元素的情况下更改元素的文本? [英] How can I change an element's text without changing its child elements?

查看:110
本文介绍了如何在不更改其子元素的情况下更改元素的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);).

这篇关于如何在不更改其子元素的情况下更改元素的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆