From MDN:
Internet Explorer introduced element.innerText. The intention is pretty much the same [as textContent] with a couple of differences:
Note that while textContent gets the content of all elements, including <script>
and <style>
elements, the mostly equivalent IE-specific property, innerText, does not.
innerText is also aware of style and will not return the text of hidden elements, whereas textContent will.
As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.
So innerText
will not include text that is hidden by CSS, but textContent
will.
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
In case you missed that, let me repeat it more clearly: Do not use .innerHTML
unless you specifically intend to insert HTML within an element and have taken the necessary precautions to ensure that the HTML you are inserting cannot contain malicious content. If you only want to insert text, use .textContent
or if you need to support IE8 and earlier, use feature detection to switch off between .textContent
and .innerText
.
A main reason that there are so many different properties is that different browsers originally had different names for these properties, and there still isn't complete cross-browser support for all of them. If you are using jQuery, you should stick to .text()
since that is designed to smooth out cross-browser differences.*
For some of the others: outerHTML
is basically the same as innerHTML
, except that it includes the start and end tags of the element it belongs to. I can't seem to find much description of outerText
at all. I think that is probably an obscure legacy property and should be avoided.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…