Alternative for innerHTML?

前端 未结 12 696
遇见更好的自我
遇见更好的自我 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 13:57

    If you only want to change plain text, then there's a quicker solution that relies on standards:

    document.getElementById("one").firstChild.data = "two";
    

    Anyway, please note that innerHTML is going to be part of the upcoming HTML 5 standard.

    0 讨论(0)
  • 2020-12-04 13:58

    insertAdjacentHTML() is the way to go. Read more: Click for documentation

    0 讨论(0)
  • 2020-12-04 13:59

    Simple.

    Replace text.innerHTML = 'two' with text.firstChild.nodeValue = 'two'.

    0 讨论(0)
  • 2020-12-04 14:00

    The better way of doing it is to use document.createTextNode. One of the main reasons for using this function instead of innerHTML is that all HTML character escaping will be taken care of for you whereas you would have to escape your string yourself if you were simply setting innerHTML.

    0 讨论(0)
  • 2020-12-04 14:06

    The recommended way is through DOM manipulation, but it can be quite verbose. For example:

    // <p>Hello, <b>World</b>!</p>
    var para = document.createElement('p');
    para.appendChild(document.createTextNode('Hello, '));
    
    // <b>
    var b = document.createElement('b');
    b.appendChild(document.createTextNode('World');
    para.appendChild(b);
    
    para.appendChild(document.createTextNode('!'));
    
    // Do something with the para element, add it to the document, etc.
    

    EDIT

    In response to your edit, in order to replace the current content, you simply remove the existing content, then use the code above to fill in new content. For example:

    var someDiv = document.getElementById('someID');
    var children = someDiv.childNodes;
    for(var i = 0; i < children.length; i++)
        someDiv.removeChild(children[i]);
    

    But as someone else said, I'd recommend using something like jQuery instead, as not all browsers fully support DOM, and those that do have quirks which are dealt with internally by JavaScript libraries. For example, jQuery looks something like this:

    $('#someID').html("<p>Hello, <b>World</b>!</p>");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题