How to add multiple divs with appendChild?

前端 未结 4 561
挽巷
挽巷 2020-12-13 18:03

I am trying to make a chessboard using javascript and creating 64 divs with it.
The problem is, that it creates only the first div.
Here is the code:



        
4条回答
  •  难免孤独
    2020-12-13 18:55

    As t-j-crowder has noted, the OP's code only creates one div. But, for googlers, there is one way to append multiple elements with a single appendChild in the DOM: by creating a documentFragment.

    function createDiv(text) {
      var div = document.createElement("div");
      div.appendChild(document.createTextNode(text));
      return div;
    }
    
    var divs = [
      createDiv("foo"),
      createDiv("bar"),
      createDiv("baz")
    ];
    
    var docFrag = document.createDocumentFragment();
    for(var i = 0; i < divs.length; i++) {
      docFrag.appendChild(divs[i]); // Note that this does NOT go to the DOM
    }
    
    document.body.appendChild(docFrag); // Appends all divs at once
    

提交回复
热议问题