Difference between innerText, innerHTML, and childNodes[].value?

前端 未结 11 1259
别跟我提以往
别跟我提以往 2020-11-22 06:57

What is the difference between innerHTML, innerText and childNodes[].value in JavaScript?

11条回答
  •  无人及你
    2020-11-22 07:47

    The examples below refer to the following HTML snippet:

    Warning: This element contains code and strong language.

    The node will be referenced by the following JavaScript:

    var x = document.getElementById('test');
    


    element.innerHTML

    Sets or gets the HTML syntax describing the element's descendants

    x.innerHTML
    // => "
    // =>   Warning: This element contains code and strong language.
    // => "
    

    This is part of the W3C's DOM Parsing and Serialization Specification. Note it's a property of Element objects.


    node.innerText

    Sets or gets the text between the start and end tags of the object

    x.innerText
    // => "Warning: This element contains code and strong language."
    
    • innerText was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016, innerText was adopted by the WHATWG and was added to Firefox in v45.
    • innerText gives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means:
      • innerText applies text-transform and white-space rules
      • innerText trims white space between lines and adds line breaks between items
      • innerText will not return text for invisible items
    • innerText will return textContent for elements that are never rendered like