JavaScript innerHTML property

The innerHTML is a property of document object (DOM) which is used to get or set the content of HTML elements.

You can set HTML content of any element including <html>, <body> tags by using JavaScript innerHTML.

See an example of innetHTML property

Following are few examples of using innerHTML with code but let us first look at its syntax:

Syntax to use innerHTML

This is how you may use the innerHTML property to set content:

HTMLelement.innerHTML = “content here”;


document.getElementById(“divex”).innerHTML = “content here”;

Now let us look at examples of using innerHTML.

JS innerHTML example to set div content

Following is an example to use innerHTML where we will set the content of div element. The div already contains some text. As you click on the button, the innerHTML property will be used to change the content of div.

Experience this example online

As you can see, the div element content is changed by using innerHTML.

innerHTML example to add HTML tags

Not only you can change the text by using innerHTML JavaScript but also you can add HTML tags as well. Following example adds <p> tag inside a div tag by using innerHTML property. Click the following link or image to see online demo:

Experience this example online

As you click on the button, the <p> tag is added by using innerHTML property. First, we get div content by using innerHTML and then the paragraph is given its own style i.e. green border is added.

document.getelementbyid innerhtml example to get content

As mentioned earlier, you can use the innerHTML property to get or set the content. In the above section, we have shown how to use innerHTML to set the content.

The following example shows how to use innerHTML property to get the content and then we will show returned content in an alert.

Experience this example online

You can see, the alert is showing the content of div element.

Related topics: JavaScript StringgetElementByid method