[英]How can I replace this text in an HTML element?
I have an string that shows up "Banana" 我有一个字符串显示“香蕉”
I want to replace it with "Apple" 我想用“ Apple”代替它
This is what I have 这就是我所拥有的
<span id="Fruit">Banana</span>
This is the script I'm using. 这是我正在使用的脚本。
var td1 = document.getElementById('Fruit');
var text = document.createTextNode("Apple");
td1.appendChild(text);
And this is what it shows up as. 这就是它所显示的。
BananaApple 香蕉苹果
<span id="Fruit">
"Banana"
"Apple"
</span>
How can I get rid of Banana and just replace it with Apple? 我该如何摆脱香蕉而仅将其替换为苹果?
<span id="Fruit">Apple</span>
只需更新innerHTML: http : //jsfiddle.net/SNtmL/
document.getElementById('Fruit').innerHTML = "Apple";
Assuming a single textNode
: 假设一个
textNode
:
var td1 = document.getElementById('Fruit'),
text = document.createTextNode("Apple");
td1.replaceChild(text,td1.firstChild);
Or: 要么:
var td1 = document.getElementById('Fruit');
td1.firstChild.nodeValue = 'Apple';
Or: 要么:
var td1 = document.getElementById('Fruit'),
text = 'textContent' in document ? 'textContent' : 'innerText';
td1[text] = 'Apple';
References: 参考文献:
You don't want a new text node, you want to alter the existing one. 您不需要新的文本节点,而是要更改现有的文本节点。
A quick and dirty solution is: 一个快速而肮脏的解决方案是:
document.getElementById("Fruit").innerHTML = "Apple";
For a more efficient way in removing all nodes from within the parent, you can always use the while()
conditional: 为了更有效地从父级中删除所有节点,可以始终使用
while()
条件:
var td1 = document.getElementById("Fruit"), text = document.createTextNode("Apple");
while(td1.hasChildNodes()) {
td1.removeChild(td1.firstChild);
}
td1.appendChild(text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.