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:
Example
Create a div in an HTML element using <div> tag and associate an id “insertText”
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:
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:
Example
Here, we will add the text in the div element using the innerText attribute:
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.