innerHTML ExamplesΒΆ

The general syntax for the innerHTML property is:

element.innerHTML

The innerHTML property of elements reads and updates the HTML and or text that is inside the element.

Note

The innerHTML value for empty elements is empty string "".

Example

 1<!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>DOM Examples</title>
 5   </head>
 6   <body>
 7      <h1>innnerHTML Example</h1>
 8
 9      <h2>Yellow Fruits</h2>
10      <ul class="yellow">
11         <li>Banana</li>
12      </ul>
13
14      <script>
15         let ul = document.querySelector(".yellow");
16         console.log(ul.innerHTML.trim());
17      </script>
18   </body>
19</html>

Console Output

<li>Banana</li>

Tip

Use .trim to remove the whitespace around the value of .innerHTML

As mentioned above innerHTML can be used to read and update the contents of an element. innerHTML is so powerful that you can pass in strings of HTML.

Example

 1<!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>DOM Examples</title>
 5   </head>
 6   <body>
 7      <h1>innnerHTML Example</h1>
 8
 9      <h2>Yellow Fruits</h2>
10      <ul class="yellow">
11         <li>Banana</li>
12      </ul>
13
14      <script>
15         let ul = document.querySelector(".yellow");
16         // Add a <li> to the list
17         ul.innerHTML += "<li>Lemon</li>";
18         console.log(ul.innerHTML.trim());
19      </script>
20   </body>
21</html>

Console Output

<li>Banana</li>
<li>Lemon</li>