How to only change the text in a DOM element without replacing any child elements

前端 未结 7 1254
一个人的身影
一个人的身影 2021-01-17 17:58

Hi I have a simple html structure

Title text inner text

What I want is to replace only the te

7条回答
  •  暖寄归人
    2021-01-17 18:24

    The following will work.

    var h1 = document.getElementById("h1"),
        children = Array.prototype.slice.call(h1.children),
        newText = document.createTextNode("Hello. ");
    
    h1.innerHTML = "";
    h1.appendChild(newText);
    
    while(children) {
        h1.appendChild(children.shift());
    }
    

    http://jsfiddle.net/TFYmv/

    Basically what you're doing is taking a picture of all the children in a specific element, changing the element completely, then re-appending all the previous children back onto the parent element using the picture we took.

提交回复
热议问题