innerHTML and textContent

Tor Francis - Nov 21 '22 - - Dev Community

Hey all I'd like to go over a HTML concept about some differences in properties of HTML and when they are rendered to the DOM.

As a beginner like myself, the difference between innerHTML and textContent did not seem very different until ran into a problem on a project I was working on.

The first web app I built was a mood playlist site that used the Spotify API to render playlist based on input of the user's mood.
If you've used Spotify before or any digital music app then your probably aware that you can create and publish a playlist.

The Problem

Image description

I typically use textContent when rendering just text to the DOM because I knew what data was going to be. However, when I didn't know what my data was going to be, it became a learning opportunity.

I realized that my Spotify data had other html elements inside of what I thought was just text. To be specific, it was string.

Image description

W3School says that textContent sets the text content of the specified node. It also says that textContent returns the text content of the element and all descendances, with spacing and CSS hidden text, but without tags.

So why does it have the tag?

We are returning just the string with HTML inside of it. If we look at MDN's description of innerHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML, it set's the HTML from the element. I wanted to have the html from my data reflected on the DOM so I need innerHTML to parsed the string into HTML.

Image description

It's working now! Thank you for reading my blog post!

. . . . . . .