JavaScript

Inserting HTML Into a div – JavaScript

In many cases, there is a need to add data dynamically on the websites, such as on social media forums, online stores, news Websites, dashboards, and so on. More specifically, any website displaying changing data or content may require dynamic updates using JavaScript or other web development tools.

This article will describe how to insert an HTML into a div element in JavaScript.

How to Insert HTML Into a div Using JavaScript?

As JavaScript is a dynamic language and is used dynamically. So, for this purpose, use the JavaScript prebuilt attributes. To insert an HTML into a div, utilize the following approaches:

Method 1: Insert HTML Into a div Using the “innerHTML” Property

Use the “innerHTML” property for inserting the HTML into a div. It can retrieve the HTML content of an element as a string or set new HTML content for an element, including text or HTML tags.

Syntax

Use the given syntax for innerHTML property to add HTML into a div in JavaScript:

element.innerHTML

Example

Create a div in an HTML element using <div> tag and associate an id “insertText

<div id="insertText"></div>

In a JavaScript file or the <script> tag, get the reference of the div element using its assigned id and use the “innerHTML” attribute to set the text with the anchor link:

document.getElementById("insertText").innerHTML = "Welcome to <a href = 'https://linuxhint.com'>Linuxhint</a>";

As you can see that the text with the link has been successfully inserted on the page using the JavaScript:

Method 2: Insert HTML Into a div Using the “innerText” Property

Another way to insert HTML into a div is to use the “innerText” property. It can get/fetch the HTML element’s text content or set new text content for an HTML element.

Syntax

Utilize the following syntax for innerText property:

element.innerText

Example

Here, we will add the text in the div element using the innerText attribute:

document.getElementById("insertText").innerText = "Hy! I'm inserting in this div using the 'innerText' Property ";

Output

That’s all about inserting HTML into a div using JavaScript.

Conclusion

For inserting HTML tags and text into an HTML div element, use the “innerHTML” property, and for inserting only text on the div element, use the “innerText” property. This article described the ways to insert an HTML into a div using JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.