What is innerHTML in JavaScript?

The innerHTML property is used to set and get the HTML content within the element.

Syntax

Get HTML Content

let htmlString = element.innerHTML;

Set HTML content

element.innerHTML = htmlString;

When we set the innerHTML of an element, all the child nodes of the element are replaced with the passed HTML contentThe passed HTML String is parsed internally..

Example

Console

In the code above, we have created a div and added some content to it.

  • We access the innerHTML property of the div element to get the HTML of the div.

  • We set the value to the innerHTML property of the div element to set the HTML of the div.


Points to be noted

  1. When we set the following:
element.innerHTML = ""

This removes all the child nodes of the element.


  1. When we set the following:
document.body.innerHTML = "";

This erases the entire body of the webpage.


  1. When we get the HTML content through the innerHTML property, if the HTML String contains the &, <, > character, then it will be replaced by the &amp;, &lt;, &gt; entities, respectively.
 & - &amp; 
 < - &lt;
 > - &gt;

  1. The <script> tag inserted with innerHTML will not execute.
div.innerHTML = <script> alert(1) </script>

The code above will not be executed or added as a string to the div.

Free Resources