Creating multiple divs using JavaScript example.

How to Create Multiple Divs Using JavaScript?

In this tutorial, you will learn how to create multiple div elements with a fixed width and write a paragraph in each div element using JavaScript. The div elements will be arranged in a flex grid layout, where they will be automatically distributed across multiple rows. We will be using an array of text elements (strings) as the source of the paragraphs. By the end of this tutorial, you will have a good understanding of how to create a flex grid layout with div elements and populate them with text using JavaScript.

Creating Multiple Divs Using JavaScript Example

Here is a sample program that creates multiple div elements with a width of 200px and writes a paragraph from an array in each div element. The array has 50 text elements (strings). The div elements are arranged in a flex grid layout.

const textArray = [
  "Text element 1",
  "Text element 2",
  "Text element 3",
  "Text element 4",
  "Text element 5",
  "Text element 6",
  "Text element 7",
  "Text element 8",
  "Text element 9",
  "Text element 10",
  "Text element 11",
  // ...
  "Text element 50"

const container = document.createElement("div"); = "flex"; = "wrap";

textArray.forEach((text) => {
  const div = document.createElement("div"); = "200px"; = "10px"; = "1px solid #ddd"; = "5px"; = "aliceblue";

  const p = document.createElement("p");
  p.innerText = text;



This program creates a div element that serves as the container for the flex grid layout. It sets the display and flex-wrap style properties of the container to flex and wrap, respectively. This creates a flex grid layout where the div elements are arranged in multiple rows.

The program then iterates through the elements in the textArray and creates a div element for each element. It sets the width of each div element to 200px and adds a margin of 10px to each div element. Also sets, the border, padding and background.

The program then creates a p element and sets its innerText property to the current element from the textArray. It then appends the p element to the div element and the div element to the container.

Finally, the program appends the container to the body element of the document. This will make the div elements with the text paragraphs visible on the webpage.


See the Pen Creating multiple Divs using JavaScript by Vinish Kapoor (@foxinfotech) on CodePen.


Written by Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of and a question and answer forum for developers. You can connect with me on Facebook and Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *