How to Create Multiple Divs Using JavaScript?

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");
container.style.display = "flex";
container.style.flexWrap = "wrap";

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

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

  container.appendChild(div);
});

document.body.appendChild(container);

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.

Output:

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

Related: