I have the following HTML element:
<p id="myP">Some text<span onclick="myFunc()"> to change</span></p>
My idea is to replace "Some text" with "Some other text" when someone clicks on the "to change" span. So my first try was:
function myFunc(){
var myP = document.getElementById("myP");
myP.innerText = "Some other text";
}
... However, I have already learned from my mistakes that this would over-ride not only the text, but also the span element nested in the p. So, using the learning of the last time, I've tried to rather create a text node:
function myFunc(){
var myP = document.getElementById("myP");
myP.appendChild(document.createTextNode("Some other text"));
}
However this is clearly wrong, because it would append the text and not replace it. How should I write my JavaScript function to obtain the pure replacement of Some text with Some other text, without however affecting the nested span?
I know this might seem a basic question, but I'm a complete beginner and don't know how well yet how to treat with HTML objects. Thanks in advance
NOTE I think that I could do simply this:
myP.innerText = "Some other text<span onclick="myFunc()"> to change</span>"
... but apart for being complicated because this is a minimized example w.r.t. the real code, I imagine it's the most unelegant solution ever, so I would like to learn the proper way.
Just get the textNode
function myFunc(){
var myP = document.getElementById("myP").firstChild;
myP.nodeValue = "Some other text";
}
<p id="myP">Some text<span onclick="myFunc()"> to change</span></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With