JavaScript Code

How to set innerHTML of a div using JavaScript?

Tutorials using JS

Set inner HTML of div

Given a div element in HTML document, set inner HTML of the div element using JavaScript.


To set inner HTML of a div element in the document using JavaScript, we can use Element.innerHTML property. Get the div element, and assign the required inner HTML value to the innerHTML property of the div element.

const myDiv = document.getElementById("myDiv");
myDiv.innerHTML = '<p>Hello World!</p> <p>Welcome!</p>';


In the following HTML code, we have a button element and a div element. When user clicks on the button, we set the inner HTML of the div element with the value <p>Hello World!</p> <p>Welcome!</p>.

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<div id="myDiv"></div>

//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //get div element
    const myDiv = document.getElementById("myDiv");
    //set inner HTML for the div
    myDiv.innerHTML = '<p>Hello World!</p> <p>Welcome!</p>';


Copyright @2022