Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #dynamically #Element

How to create multiple div dynamically in JavaScript?

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:

  1. We define a function createDivs that takes the number of divs to create as a parameter.
  2. 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:

  1. We access the container element by its ID.
  2. 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.

save
listen
AI Answer
Write Your Answer
loading
back
View All