Alternative for innerHTML?

前端 未结 12 797
遇见更好的自我
遇见更好的自我 2020-12-04 13:34

I\'m wondering if there\'s a way to change the text of anything in HTML without using innerHTML.

Reason I\'m asking is because it\'s kinda frowned upon by the W3C. I

12条回答
  •  隐瞒了意图╮
    2020-12-04 14:08

    I sometimes find it helpful to store a direct reference to the text node if I am going to be updating it regularly. I do something like this:

    var dynamicText = myDiv.appendChild(document.createTextNode("the initial text"));
    

    And then whenever I need to update it, I just do this:

    dynamicText.nodeValue = "the updated text";
    

    This prevents having to walk the DOM or add or remove any children.

提交回复
热议问题