How to Add HTML to a Div Using JavaScript?

Estimated read time 2 min read

You can use JavaScript to add HTML content to a div element by accessing the element through its id attribute and then modifying its innerHTML or textContent properties.

Here is an example of how to add HTML content to a div element with the id “myDiv”:

// Get the div element by its ID
var myDiv = document.getElementById("myDiv");

// Add HTML content to the div using innerHTML or textContent
myDiv.innerHTML = "<h1>This is a heading</h1><p>This is a paragraph.</p>";

In this example, we use the document.getElementById() method to get the div element with the id “myDiv” and assign it to the myDiv variable. We then set the innerHTML property of the myDiv element to a string containing the HTML code that we want to add to the div.

Alternatively, you can use the textContent property to add text content to the div element without including any HTML markup. Here is an example:

// Get the div element by its ID
var myDiv = document.getElementById("myDiv");

// Add text content to the div using textContent
myDiv.textContent = "This is some text content.";

In this example, we use the textContent property of the myDiv element to set the text content of the div to the string “This is some text content.” without any HTML markup.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply