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
4 Answers
Reset to default 8Just 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);