Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

tal Shnitzer
PLUS
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
229,670 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:

Hello

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:

<h1>Hello</h1>