Skip to content

How to appendChild(element) many times. (The same element)

My question is: Is that possible to add the same element without rewriting the same variable. I am creating a slider, and i need to append a div with a class slide-el into block slider. Here is a part of code

    var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
    parts = 3,

    //Main html elements
    body = document.body,
    html = document.element,

    //viewport Height and Width
    vHeight = window.innerHeight,
    vWidth = window.innerWidth,

    sliderBody = _id("slider"),
    btnLeft = _id("btn-left"),
    btnRight = _id("btn-right"),

    urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
            "http://www.wallpapereast.com/static/images/pier_1080.jpg",
            "http://www.wallpapereast.com/static/images/pier_1080.jpg",
            "http://www.wallpapereast.com/static/images/pier_1080.jpg"];

    slide = _createEl("div");
    slide.className += "slide-el";

function _id(el){
  return document.getElementById(""+ el +"");
}
function _createEl(el){
  return document.createElement(""+ el +"");
}
window.onload = function(){
  slideLayout();
}

function slideLayout(){
  for(var i=0; i < urls.length; i++){
    sliderBody.appendChild(slide);
  }
}

The problem is that I can’t append the same element that many times. It just creates one element instead of 4.

For you to understand better I made a fiddle:

https://jsfiddle.net/ud7dvn3z/

Answer

appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.

for(var i = 0; i < urls.length; i++){
  sliderBody.appendChild(slide.cloneNode(true));
}