Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create multiple divs with the same class javascript

Tags:

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>
like image 619
Yamaha32088 Avatar asked Dec 01 '13 03:12

Yamaha32088


People also ask

Can multiple divs have the same class?

you can't have the same name for two “divs” or “classes”.

Can two tags have same class?

Explanation: Even if the two elements do not have the same tag name, they can have the same class name, and get the same styling.

Can you have multiple divs?

Creating Web Layout using Div Tag The div tag is a container tag inside div tag we can put more than one HTML element and can group together and can apply CSS for them.


3 Answers

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.

like image 162
Thomas Kelley Avatar answered Oct 08 '22 05:10

Thomas Kelley


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>
like image 30
Tom Chung Avatar answered Oct 08 '22 07:10

Tom Chung


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>
like image 26
NenadP Avatar answered Oct 08 '22 07:10

NenadP