[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/createtextnode-vs-innerhtml [Back]  [Original]

createTextNode vs innerHTML vs textContent
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    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 will do exactly the same?

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

    Answer: 1 and 3.

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

    Heres an example:

    <div id="elem1"></div>
    <div id="elem2"></div>
    <div id="elem3"></div>
    <script>
      let text = '<b>text</b>';
    
      elem1.append(document.createTextNode(text));
      elem2.innerHTML = text;
      elem3.textContent = text;
    </script>

    Web Proxy Viewer  |  New URL  |  Original Page