JavaScript JavaScript and the DOM Making Changes to the DOM Creating New DOM Elements

tal Shnitzer
tal Shnitzer
Pro 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
172,328 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: