Back to the lesson

createTextNode vs innerHTML vs textContent

importance: 5

We have an empty DOM element elem and a string text.

Which of these 3 commands do exactly the same?

  1. elem.append(document.createTextNode(text))
  2. elem.innerHTML = text
  3. elem.textContent = text

Answer: 1 and 3.

Both commands result in adding the text “as text” into the elem.

Here’s an example:

<div id="elem1"></div>
<div id="elem2"></div>
<div id="elem3"></div>
  let text = '<b>text</b>';

  elem2.textContent = text;
  elem3.innerHTML = text;