how to create multiple div dynamically in javascript

Creating multiple div elements dynamically in JavaScript is a common task when working with the Document Object Model (DOM). This can be achieved in several ways, including the following:

Using the createElement method:

The createElement method creates a new HTML element with a specified tag name and returns a reference to it. You can use this method in a loop to create multiple elements and append them to a parent element in the DOM. For example:

how to create multiple div dynamically in javascript
how to create multiple div dynamically in javascript

In this example, the parent variable is a reference to an element in the DOM with the ID “parent”. The loop creates 10 div elements and sets their inner HTML to a string that includes their index. Finally, the elements are appended to the parent element using the appendChild method.

Using innerHTML:

The innerHTML property of an element allows you to set or get its HTML content as a string. You can use this property in a loop to create multiple elements and add them to a parent element in the DOM. For example:

how to create multiple div dynamically in javascript
how to create multiple div dynamically in javascript

In this example, the html variable is a string that holds the HTML content for the div elements. The loop appends the HTML for each element to the string. Finally, the innerHTML property of the parent element is set to the html string, which adds the elements to the DOM.

Note that using innerHTML to add multiple elements to the DOM can be faster than using createElement and appendChild, but it can also be less efficient because it can cause the browser to perform a full re-render of the page.

In conclusion, creating multiple div elements dynamically in JavaScript is a straightforward process that can be accomplished using the createElement method or the innerHTML property. The choice of method depends on the specific requirements of your use case, such as performance and maintainability.

By umarbwn