Update the HTML markup of a DOM element with JavaScript

In JavaScript, the HTML element's innerHTML property can be used to set or get the HTML markup within the element. This property returns a DOM string containing the HTML serialization of all child elements.

If you set a new value of innerHTML, it will remove all the element's child nodes and replace them with HTML nodes created by parsing the HTML string.

Let us say we have the following <div> element somewhere in the document:

<div id="hint">
    <p>Learn JavaScript for free!</p>

To get the current HTML markup of the above HTML, use the following JavaScript:

// grab element
const div = document.querySelector('#hint')

// get current HTML markup

// <p>Learn JavaScript for free!</p>

To replace the existing HTML markup completely, simply set a new value of innerHTML like below:

// replace existing markup
div.innerHTML = 'span>Hey, there!</span>'

To add new elements before the current HTML markup, do the following:

div.innerHTML = 'span>Hey, there!</span>' + div.innerHTML

To append HTML contents after the existing markup:

div.innerHTML += 'span>Hey, there!</span>'

The new markup can be any valid HTML string, including simple plain text:

div.innerHTML = 'This is plain text'

Read Next: How to create a DOM element using JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.