innerHTML Vs. textContent: The subtle difference.

innerHTML Vs. textContent: The subtle difference.

At first glance, both properties look like they do the same thing.

While innerHTML provides a simple and convenient way to create HTML templates as strings and inject them into the DOM [Document Object Model], textContent only lets you create plain texts as strings.

Now, let's break it down.

textContent in action:

Say we want to output "I love JavaScript"

<p id="output"></p>

<script>
    document.getElementById("output").textContent = "I love Javascript";
</script>

innerHTML in action:

innerHTML can do everything textContent can, plus a higher level of DOM manipulation. For instance;

Let's output "I love JavaScript"

Note: "I" is Italicised, "love" is bold, and let's assume "JavaScript" is in red

<p id="output"></p>

<script>
    document.getElementById("output").innerHTML = "<em>I</em> <strong>love</strong> <span style='color: red;'>JavaScript</span>";
</script>

Conclusion:

innerHTML is richer, as you can get more fanciful with it. But if you only aim to return text content, go ahead with textContent.

Hope you find this helpful.

Happy to learn from you.

How would you use these properties?