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
Example
In the code above, we have created a div and added some content to it.
-
We access the
innerHTMLproperty of thedivelement to get the HTML of thediv. -
We set the value to the
innerHTMLproperty of thedivelement to set the HTML of thediv.
Points to be noted
- When we set the following:
element.innerHTML = ""
This removes all the child nodes of the element.
- When we set the following:
document.body.innerHTML = "";
This erases the entire body of the webpage.
- When we get the HTML content through the
innerHTMLproperty, if the HTML String contains the&, <, >character, then it will be replaced by the&,<,>entities, respectively.
& - &
< - <
> - >
- The
<script>tag inserted withinnerHTMLwill not execute.
div.innerHTML = <script> alert(1) </script>
The code above will not be executed or added as a string to the div.