最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

create multiple divs with the same class javascript - Stack Overflow

programmeradmin2浏览0评论

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>

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>
Share Improve this question asked Dec 1, 2013 at 3:04 Yamaha32088Yamaha32088 4,16310 gold badges53 silver badges104 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 6

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.

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>

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>

发布评论

评论列表(0)

  1. 暂无评论