innerHTML Vs. textContent: The subtle difference.

giwajossy

Giwa Jossy

Posted on November 13, 2020

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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?

💖 💪 🙅 🚩
giwajossy
Giwa Jossy

Posted on November 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related