Difference between innerHTML, innerText and textContent

understanding the uses of each by javascript snippets

ยท

2 min read

Difference between innerHTML, innerText and textContent

Table of contents

No heading

No headings in the article.

While dom manipulation we should have an idea about the elements where we are manipulating . So in these article we will discuss one main idea about innerHTML, innerText, TextContent with examples.

Lets take an example -

<p id="select"> We are including text in <em>italics</em> and a special character like & </p>

The above example will be displayed as -

We are including text in ๐˜ช๐˜ต๐˜ข๐˜ญ๐˜ช๐˜ค๐˜ด and a special character like &

Now lets take a variable to select p element -

const newVar = document.querySelector("#select");

Now, if we call innerHTML, innerText, textContent on these variable, it will return us -

  • innerHTML - It will return the text content with spaces, line breaks, html tags between the newVar . It will also return the special characters like '&' as '&amp'.

newVar.innerHTML \\=> We are including text in <em>italics</em> and a special character like &amp

  • innerText - It will return plain text in the tag with no formatting

new.innerText \\=> We are including text in italics and a special character like &

  • textContent - it will return the text content in the tag with spaces, line breaks and other formatings

new.innerText \\=> We are including text in italics and a special character like &

So, we have seen the main difference between innerHTML, innerText, TextContent which is vey important and should be kept in mind during manipulating the elements.

ย