如何在HTML元素中替换此文本?

Rag*_*hav 1 html javascript dom dom-manipulation

我有一个字符串显示"香蕉"

我想用"Apple"替换它

这就是我所拥有的

<span id="Fruit">Banana</span>
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的脚本.

    var td1 = document.getElementById('Fruit');
    var text = document.createTextNode("Apple");
    td1.appendChild(text);
Run Code Online (Sandbox Code Playgroud)

这就是它所表现出来的.

BananaApple

    <span id="Fruit">
    "Banana"
    "Apple"
    </span>
Run Code Online (Sandbox Code Playgroud)

我如何摆脱香蕉,只需用苹果取而代之?

<span id="Fruit">Apple</span>
Run Code Online (Sandbox Code Playgroud)

Dal*_*las 8

只需更新innerHTML:http://jsfiddle.net/SNtmL/

document.getElementById('Fruit').innerHTML = "Apple";
Run Code Online (Sandbox Code Playgroud)


Dav*_*mas 5

假设一个textNode:

var td1 = document.getElementById('Fruit'),
    text = document.createTextNode("Apple");
td1.replaceChild(text,td1.firstChild);
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

要么:

var td1 = document.getElementById('Fruit');
td1.firstChild.nodeValue = 'Apple';
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

要么:

var td1 = document.getElementById('Fruit'),
    text = 'textContent' in document ? 'textContent' : 'innerText';
td1[text] = 'Apple';
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

参考文献: