DEV Community

Cover image for innerText vs innerHTML
Mahesh Deshmukh
Mahesh Deshmukh

Posted on

innerText vs innerHTML

Introduction

I started learning JavaScript a month or two ago via neogCamp level0. That's where I first encounter these two properties of JavaScript. Sometimes I was using innerText to get my work done and sometimes innerHTML honestly speaking I never paid much attention to what I was using I relied too much on my code editor. But, let's now talk about what to use where.

innerText

In simple words, this property lets you put text(string) inside the HTML element from the JavaScript side. innerText retrieves and sets the content of the tag as plain text. So, whatever string you are passing innerText will place it as plain text inside your HTML element for viewers to see. An example of that will be like this.

<html>
<body>
<div style="text-align:center" id="trial1"></div>

<script>
const try1 = document.querySelector("#trial1");
try1.innerText = "This is innerText";
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

An image showing example of innerText html code

innerHTML

Now as its name suggests this property lets you print content between HTML tags, including text information. Unlike innerText, though, innerHTML lets you work with HTML-rich text and doesn't automatically encode and decode text. That means you can use innerHTML to pass normal text as well but, you cant use innerText in place of innerHTML. An example of innerHTML will be like this.

<tml>
 <body>
    <div style="text-align: center;" id="trial2"></div>

<script>
   const try2 = document.querySelector("#trial2");
   try2.innerHTML = `<p>This is innerHTML</p>
          <img style="width:100px;height:100px;" src="hero.jpg">`;
</script>

  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

An image showing example of innerHTML html code

comparison

<html>
<body>
    <div style="text-align: center;" id="trial1"></div>
    <div style="text-align: center;" id="trial2"></div>

<script>
   const try1 = document.querySelector("#trial1");
   const try2 = document.querySelector("#trial2");
try1.innerText ='<p>This is innerText</p><img style="width:100px;height:100px;" src="hero.jpg">';

try2.innerHTML = `<p>This is innerHTML</p><img style="width:100px;height:100px;" src="hero.jpg">`;
 </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

An image showing example of innerText & innerHTML html code

innerText is printing pure text from the given string and innerHTML is decoding the string as simple text as well as HTML element.

Top comments (1)

Collapse
 
codewave profile image
muhammad hasan

Super