Some text to ...">

Replace one text with another tag containing other tags

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 the edit button. Therefore, my first attempt:

function myFunc(){
    var myP = document.getElementById("myP");
    myP.innerText = "Some other text";
}

... However, from my mistakes I already learned that this will move not only the text, but also the span element nested in p. So, using training for the last time, I tried rather to create node text:

function myFunc(){
    var myP = document.getElementById("myP");
    myP.appendChild(document.createTextNode("Some other text"));
} 

However, this is clearly wrong, because it will add text and not replace it. How to write a JavaScript function to get a clean replacement for some text with some other text without affecting the nested range?

, , , HTML.

, :

myP.innerText = "Some other text<span onclick="myFunc()"> to change</span>"

... , , w.r.t. , , -, .

+4
4

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>
Hide result
+4

?

<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";
}
+1

node :

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>
Hide result
+1

:

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>
Hide result
+1

All Articles