innerHTML Vs Innertext Vs Textcontent
innerHTML Vs Innertext Vs Textcontent
In Javascript, there are three properties that can be used to set or return
an HTML element's content in the DOM: innerHTML, innerText, and
textContent. If you are unsure about the differences and wondering
which one to use, hopefully the following comparison will help.
1
const example4 = document.getElementById('example4')
example4.innerHTML = '<img src=x onerror="alert(\'XSS Attack\')">'
<img src=jAvascript:alert('test2')>
(2) The innerText property returns the content of all elements, except
for <script> and <style> elements. The returned content is visible plain text
without any formatting, similar to highlighting text and then copying
and pasting it. What you see is what you get.
One drawback to using innerText is that its value triggers a reflow due
to its awareness of CSS styling, which leads to decreased performance.
Reflow is when the browser recalculates page elements for re-rendering
the document. Instances that trigger reflow include resizing the browser
window or changing elements in the DOM. Reflow is computationally
expensive and should be minimized in order to improve speed,
efficiency, and user experience.
NOTE: The innerText property is not supported in Internet Explorer 9 and earlier.
2
(3) The textContent property returns the raw content with styling
inside of all elements but excludes the HTML element tags. This
includes <script> and <style> elements, whitespace, line breaks, and carriage
returns. Unlike innerHTML, textContent has better performance because
its value is not parsed as HTML. For that reason, using textContent can
also prevent Cross-Site Scripting (XSS) attacks. Unlike innerText,
textContent isn't aware of CSS styling and will not trigger a reflow. All
Node objects have textContent, whereas only HTMLElement objects
have innerText.
NOTE: The textContent property is not supported in Internet Explorer 8 and earlier.
The example below shows how each of the three properties return
the contents of the <p> element:
<p id="demo"> This element has extra spacing and contains <span>a span element</span>.
</p>
function getInnerHtml() {
console.log(document.getElementById("demo").innerHTML)
}
innerHTML returns:
" This element has extra spacing and contains <span>a span element</span>."
/*
The innerHTML property returns the text, spacing, and inner HTML element tags.
*/
function getInnerText() {
console.log(document.getElementById("demo").innerText)
}
3
innerText returns:
"This element has extra spacing and contains a span element."
/*
The innerText property returns just the visible text,
without spacing or inner HTML element tags.
*/
function getTextContent() {
console.log(document.getElementById("demo").textContent)
}
textContent returns:
" This element has extra spacing and contains a span element."
/*
The textContent property returns the text and spacing,
but without the inner HTML element tags.
*/
Prepared by: