最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I replace this text in an HTML element? - Stack Overflow

programmeradmin1浏览0评论

I have an string that shows up "Banana"

I want to replace it with "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>

I have an string that shows up "Banana"

I want to replace it with "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>
Share Improve this question edited Apr 4, 2014 at 18:39 Smern 19.1k22 gold badges77 silver badges93 bronze badges asked Aug 9, 2013 at 21:32 RaghavRaghav 1142 silver badges12 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 8

Just update the innerHTML: http://jsfiddle/SNtmL/

document.getElementById('Fruit').innerHTML = "Apple";

Assuming a single textNode:

var td1 = document.getElementById('Fruit'),
    text = document.createTextNode("Apple");
td1.replaceChild(text,td1.firstChild);

JS Fiddle demo.

Or:

var td1 = document.getElementById('Fruit');
td1.firstChild.nodeValue = 'Apple';

JS Fiddle demo.

Or:

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

JS Fiddle demo.

References:

  • Node.nodeValue.
  • Node.replaceChild().

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:

var td1 = document.getElementById("Fruit"), text = document.createTextNode("Apple");
while(td1.hasChildNodes()) {
    td1.removeChild(td1.firstChild);
}
td1.appendChild(text);
发布评论

评论列表(0)

  1. 暂无评论