Home | SkillForge Blog | innerHTML vs textContent – The Difference Between These JavaScript Properties

innerHTML vs textContent – The Difference Between These JavaScript Properties

JavaScript, Web Design

innerHTML vs. textContent, what is the difference between these JavaScript properties and which one should you use?  They do the same thing, right?  No, they actually do not.  The difference between the .innerHTML and .textContent properties is all about the HTML my friends!  textContent renders text and only text, and innerHTML renders text with any HTML applied to it.  To illustrate, here’s a quick example you can try in your chosen text editor (just copy and paste it in if you want):

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>innerHTML vs textContent</title>
</head>
<body>
<h2>textContent:</h2>
<!–Div that will hold the textContent text–>
<div id=”textContentExample”></div>
<h2>innerHTML:</h2>
<!–Div that will hold the innerHTML text–>
<div id=”innerHTMLExample”></div>

<script>
/*selects the div with the id of textContentExample and sets it’s textContent property to the following string*/
document.getElementById(“textContentExample”).textContent = “<b>I am truly bold with textContent!</b>”;

/*selects the div with the id of innerHTMLExample and sets it’s innerHTML property to the following string*/
document.getElementById(“innerHTMLExample”).innerHTML = “<b>No, I am truly the boldest with innerHTML</b>”;
</script>
</body>
</html>

 

Once that has been entered into the editor, saved as a .html file, and ran you will see this result:

innerhtml-vs-textcontent

The key to all of this is in this part of the code:

document.getElementById(“textContentExample”).textContent = “<b>I am truly bold with textContent!</b>”;

document.getElementById(“innerHTMLExample”).innerHTML = “<b>No, I am truly the boldest with innerHTML</b>”;

In the first statement, we use textContent to put the string “<b>I am truly bold with textContent</b>” onto the page and we can see that it doesn’t apply the HTML, it just writes the <b> tags out to the page as text.  In the second statement, we use innerHTML and the result is applying the HTML to the text bolding the sentence.

If you want to learn more, SkillForge has a JavaScript Training Course that goes over this and much more.