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