Yamaha32088
Yamaha32088

Reputation: 4163

create multiple divs with the same class javascript

I am new to JavaScript and would like to know how I can create multiple divs dynamically with the same class name. I have the following code but it only creates one instance of the div.

<div id="wrapper">
    <div id="container">
        <div id="board">
            <script>
                var board = document.createElement('div');
                board.className = "blah";

                for(x=0; x<9;x++) {
                document.getElementById('board').appendChild(board);
                }
            </script>
        </div>
    </div>
</div>

Upvotes: 5

Views: 38342

Answers (3)

NenadP
NenadP

Reputation: 647

Others did answer the question in a nutshell; here is one approach which addresses some issues that are present in the your and proposed code snippets, and maybe gives your some insight for further exploration. I hope it helps :)

To extend a script a little bit, this solution creates every element by using function createDiv, and references to individual divs are stored in an array, so you can modify the content of each div by modifying array elements, which are referring to DOM elements. (in this example, I modify 6th div for demonstration sake)

Notes:

  • All of your code is thrown in a global object, it's good practice to encapsulate your code, here in immediately invoked anonymous function.
  • x would be thrown in a global object even if encapsulated, you need always to declare your variables with a var keyword. Here I declare all vars needed upfront in one statement, which is also a good practice;
  • It is convention to use "i" for loop iterator variable.
  • Avoid "magic numbers" (9), rather create a variable that will describe what you do in your code. It is good if the code describes what it does.
  • Also in this example, we avoid declaring "board" on each loop iteration (the element where your divs get appended.)
  • Test your code in JSLint - great tool to validate your scripts. (this will pass the test, given that you set indentation to 2.
  • "use strict" - read here.

/*jslint browser:true */

(function () {
  "use strict";

  function createDiv() {
    var boardDiv = document.createElement("div");

    boardDiv.className = "new-div";
    boardDiv.innerText = "I am new DIV";

    return boardDiv;
  }

  function createAndModifyDivs() {
    var board = document.getElementById("board"),
      myDivs = [],
      i = 0,
      numOfDivs = 9;

    for (i; i < numOfDivs; i += 1) {
      myDivs.push(createDiv());
      board.appendChild(myDivs[i]);
    }

    myDivs[5].className = "modified-div";
    myDivs[5].innerText = "I'm modified DIV";
  }

  createAndModifyDivs();

}());
.new-div {
color: gray;  
}

.modified-div {
color: red;  
}
<!DOCTYPE html>
<html>
  <head>
    <title>Inserting Divs</title>
  </head>
  <body>
    <div id="wrapper">
      <div id="container">
        <div id="board">
        </div>
      </div>
    </div>
  </body>
</html>

Upvotes: 2

Thomas Kelley
Thomas Kelley

Reputation: 10292

Right now, you're creating the element outside the loop, and appending that element to the DOM...again and again.

What you want to do is create a new element during every iteration of the loop. To do that, move the part where you create the new div inside the loop:

for(x=0; x<9;x++) {
    var board = document.createElement('div');
    board.className = "blah";

    document.getElementById('board').appendChild(board);
}

Now, every time the loop runs, you'll create a new element, and append that element to the element with ID #board.

It's worth pointing out that the variable you created (board) now only has scope within this loop. That means that once the loop is done, you'll need to find a different way to access the new elements, if you need to modify them.

Upvotes: 6

Tom Chung
Tom Chung

Reputation: 1422

Only a single element is created.

        <script>
            var board = document.createElement('div');
            board.className = "blah";

            for(x=0; x<9;x++) {
            document.getElementById('board').appendChild(board);
            }
        </script>

Should be written as:

        <script>
            for(x=0; x<9;x++) {
            var board = document.createElement('div');
            board.className = "blah";
            document.getElementById('board').appendChild(board);
            }
        </script>

Upvotes: 3

Related Questions