JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Hanwen Zhang
Hanwen Zhang
15,509 Points

What are the differences between textContent and innerText HTML? Thanks

What are the differences between textContent and innerText HTML? Thanks

1 Answer

Peter Vann
Peter Vann
36,049 Points

Hi Hanwen!

This is a gross oversimplification, but think of textContent as meant to be used for embedding text in an element, whereas innerHTML can be any HTML, including text, but also including other elements.

I will include more info for a more thorough explanation, though.

One important thing to note: use textContent instead of innerHTML, if all you need to imbed is text

innerHTML can introduce vulnerabilities into your code and can open your apps up to XSS attacks (usually in cases where user input gets store in a node's innerHTML)!

I recommend eventually taking this course:

https://teamtreehouse.com/library/owasp-top-10-vulnerabilities (includes info on XSS attacks)

More info:

https://betterprogramming.pub/whats-best-innertext-vs-innerhtml-vs-textcontent-903ebc43a3fc

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText

https://stackoverflow.com/questions/21311299/nodevalue-vs-innerhtml-and-textcontent-how-to-choose

https://skillforge.com/innerhtml-vs-textcontent-the-difference-between-these-javascript-properties/

https://www.microfocus.com/documentation/silk-test/200/en/silktestworkbench-help-en/SILKTEST-21EEFF3F-DIFFERENCEBETWEENTEXTCONTENTSINNERTEXTINNERHTML-REF.html

https://owasp.org/www-community/attacks/xss/#:~:text=Cross%2DSite%20Scripting%20(XSS),to%20a%20different%20end%20user.

https://www.veracode.com/security/xss

I hope that helps.

Stay safe and happy coding!

Hanwen Zhang
Hanwen Zhang
15,509 Points

Hi Peter,

Definitely helps, thank you!!!