Different use of innerText and innerHTML

While designing a dynamic web page, we often come across a requirement where we need to show some data based on user selection or according to some other parameters. In this case basically we try to change the inner content of some elements (like div, span). And also sometimes we are required to know the text or HTML content of some elements. This is where the properties innerText and innerHTML comes into picture.

The innerText property

The innerText property sets or returns the text content of an element.

Use of innerText to get text content of a node

<div>
   <span id="info"> This is an example of innerText </span>
</div>
const text = document.getElementById('info').innerText;

console.log(text); // This is an example of innerText

The innerText property returns text of the specified element node and all of its descendants node.

<div id="info">
    This is 1st level node text
    <span> This is 2nd level node text </span>
</div>
const text = document.getElementById('info').innerText;

console.log(text); 
// This is 1st level node text This is 2nd level node text

Use of innerText to set text content of a node

<p id="para"> This is initial text inside paragraph </p>
document.getElementById('para').innerText = 'Updated text inside paragraph';

Output of HTML will be:

<p id="para"> Updated text inside paragraph </p>

If the specified node contains child nodes, then innerText will replace all the child nodes with the given text.

<div id="para">
     <p> This is one paragraph </p>
     <span>
         <p> Some other paragraph </p>
     </span>
</div>
document.getElementById('para').innerText = 'This is updated text';

After setting innerText, the HTML element node would look like:

<div id="para"> This is updated text </div>

The innerHTML property

The innerHTML property sets or returns the HTML content of a specified node.

Using innerHTML to get HTML content of a node

<div id="para">
    <span> This is an example of innerHTML </span>
</div>
const html = document.getElementById('para').innerHTML;

console.log(html); // <span>This is an example of inneHTML</span>

Using innerHTML to set HTML content of a node

<div id="info">
    <p> This is one paragraph </p>
    <span>
       <p> This is child element 1 </p>
       <span> This is child element 2 </span>
    </span>
</div>
document.getElementById('info').innerHTML = '<p> This is Updated element </p>';

After updating innerHTML the HTML content would look like:

<div id="info">
    <p> This is Updated element </p>
</div>

Now you are all set to dynamically set content of any html node in your page. Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *