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 wrt 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>
Why not just implement it using another element?
<p><span id="to-change">Some text</span> <span onclick="myFunc()">to change</span></p>
function myFunc(){
document.getElementById("to-change").innerText = "Some other text";
}
Or you can replace the first text node with a new one:
function myFunc() { var myP = document.getElementById("myP"); myP.replaceChild(document.createTextNode("Some other text"), myP.childNodes[0]); }
<p id="myP">Some text<span onclick="myFunc()"> to change</span></p>
For the really simple approach:
function myFunc(){ var myP = document.getElementById("myP"); var cn = myP.childNodes[0]; // where cn.nodeType == 3 (text node) cn.textContent = "Some other text"; }
<p id="myP">Some text<span onclick="myFunc()"> to change</span></p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.