How to add multiple divs with appendChild?

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

Leave a Comment