Difference between innerHTML and innerText Property

← PrevNext →

The innerHTML property allows you to write (or add) HTML code (or markup) along with a text value. Whereas, the innerText property allows only text values to the elemnet. Let's understand this with a examples.

Let us assume, I have a <span> element and I want to assign (or add) some text to the span dynamically. I can use both "innerHTML" or "innerText" properties to add text to element. However, there's a difference.

Here's the element.

<body>
    <span id='name'></span>
</body>

First, lets see the innerHTML property.

<script>
  document.getElementById('name').innerHTML = 'Hello, I am a programmer';
</script>

The result is,

Hello, I am a programmer

Try it

👉 Next, I'll use the innerText property.

<script>
  document.getElementById('name').innerText = 'Hello, I am a programmer';
</script>

The result is,

Hello, I am a programmer

Well, the result using both the properties is similar.

Now let us assume, I want to highlight or bold the last text, the "programmer".

I'll using the innerHTML property to do this.

<script>
  document.getElementById('name').innerHTML = 'Hello, I am a <b> programmer </b>';
</script>

The result now is,

Hello, I am a programmer

Try it

If you see the text (in the script), you will notice that I have assigned "programmer" within <b>...</b> tags. The <b> is an HTML tag to bold a text. Similarly, I can assign any "markup" within the string.

However, with innerText property the entire string, with the tags, will be will displayed as plain text. See the code.

<script>
  document.getElementById('name').innerText = 'Hello, I am a <b> programmer </b>';
</script>

The result is,

Hello, I am a <b> programmer </b>

Conclusion

For plain text, use innerText property and if you want to add markup to the text like colour, underline, bold etc., use innerHTML property.

← PreviousNext →