Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) Making Changes to the DOM Creating New DOM Elements

tal Shnitzer
tal Shnitzer
Courses Plus Student 5,242 Points

innerHTML vs textContent

const descriptionInput = document.querySelector('input.description'); const descriptionP = document.querySelector('p.description'); const addItemInput = document.querySelector('input.addItemsInput'); let li = document.createElement('li');

why descriptionP.innerHTML = descriptionInput.value

but li.textContent = addItemInput.value;

why not: li.innerHTML = addItemInput.value; or descriptionP.textContent = descriptionInput.value

how do I know when to use either?

2 Answers

Steven Parker
Steven Parker
221,310 Points

You would choose "innerHTML" any time you are assigning content that might contain HTML markup tags and you wish to allow them to become part of the document. For example, assigning "<h1>Hello</h1>" to "innerHTML" will be displayed like this:


Use "textContent" instead when the values never contain any markup, or if you're not sure if they will but you don't want to allow it to be added to the document (and force it to be displayed verbatim). For example, assigning "‌<h1>Hello</h1>" to "textContent" will be displayed like this: