Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
javascript
innerhtml
communitycreator

What is innerHTML in JavaScript?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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.

RELATED TAGS

html
javascript
innerhtml
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring