[英]How can I replace this text in an HTML element?
我有一個字符串顯示“香蕉”
我想用“ Apple”代替它
這就是我所擁有的
<span id="Fruit">Banana</span>
這是我正在使用的腳本。
var td1 = document.getElementById('Fruit');
var text = document.createTextNode("Apple");
td1.appendChild(text);
這就是它所顯示的。
香蕉蘋果
<span id="Fruit">
"Banana"
"Apple"
</span>
我該如何擺脫香蕉而僅將其替換為蘋果?
<span id="Fruit">Apple</span>
只需更新innerHTML: http : //jsfiddle.net/SNtmL/
document.getElementById('Fruit').innerHTML = "Apple";
假設一個textNode
:
var td1 = document.getElementById('Fruit'),
text = document.createTextNode("Apple");
td1.replaceChild(text,td1.firstChild);
JS小提琴演示 。
要么:
var td1 = document.getElementById('Fruit');
td1.firstChild.nodeValue = 'Apple';
JS小提琴演示 。
要么:
var td1 = document.getElementById('Fruit'),
text = 'textContent' in document ? 'textContent' : 'innerText';
td1[text] = 'Apple';
JS小提琴演示 。
參考文獻:
您不需要新的文本節點,而是要更改現有的文本節點。
一個快速而骯臟的解決方案是:
document.getElementById("Fruit").innerHTML = "Apple";
為了更有效地從父級中刪除所有節點,可以始終使用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.