Get and Set the HTML Content of an Element with JavaScript innerHTML

Web Design & Web Development

In this article, I will introduce how to get and set the HTML content of an element with JavaScript innerHTML.

What is innerHTML?

To get and set the HTML content of an element, you can use the JavaScript innerHTML property.

When setting, if there is already some content in the element, that content will be overwritten.

Get the HTML content

The following example demonstrates how to get the HTML content of a specified element.

HTML

<div id="target"><h1>Plantpot</h1></div>

JavaScript

const element = document.getElementById('target');
console.log(element.innerHTML);
/* expected output:
<h1>Plantpot</h1>
*/

Set the HTML content

The following example demonstrates how to set the HTML content of a specified element.

HTML

<div id="target"><h1>Plantpot</h1></div>

JavaScript

element.innerHTML = '<h1>foo</h1>';
console.log(element.innerHTML);
/* expected output:
<h1>foo</h1>
*/