In this article, we will learn how to create multiple div elements dynamically in JavaScript.
Sometimes, you may need to generate and display several <div> elements on a web page based on user input or other dynamic factors.
Method 1: Using the createElement() Method #
You can use the createElement() method to dynamically create multiple <div> elements.
Here's the code snippet that demonstrates how to create and append multiple divs dynamically:
Explanation:
- We define a function createDivs that takes the number of divs to create as a parameter.
- Inside the loop, we create new div elements and customize their content before appending them to the container.
Method 2: Using InnerHTML Property #
Alternatively, you can utilize the innerHTML property to add multiple divs to an existing container element.
Explanation:
- We access the container element by its ID.
- Using a loop, we append new div elements with desired content to the container using the innerHTML property.
Conclusion #
In this article, we've explored two effective methods for creating multiple div elements dynamically in JavaScript.
Comments (0)