How to Create a Box and Display Words from an Array in JavaScript?

Estimated read time 2 min read

Here’s an example of how you can create boxes and display words from an array in JavaScript:

      .box {
        width: 200px;
        height: 200px;
        background-color: lightgray;
        border: 1px solid black;
        text-align: center;
        font-size: 20px;
        display: inline-block;
        margin: 10px;
    <div id="container"></div>
      const words = ["Hello", "world", "JavaScript", "array", "boxes"];
      const container = document.getElementById("container");
      for (const word of words) {
        const box = document.createElement("div");
        box.innerText = word;

This code creates a words array with some string values. Then, it selects a div element with id="container" and uses a for loop to iterate over the words array. In each iteration, it creates a new div element, adds the box class to it, sets its text content to the current word from the array, and appends it to the container element. The CSS styles the boxes with a fixed width, height, background color, border, text alignment, and font size, and adds some margin to make them spaced out from each other.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply