0

This is my code:

var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
    var newDiv=document.createElement("div"); //create a new div
    var newDiv2=document.createElement("div") //create a new div
    newDiv.innerHTML=array[index];
    newDiv.draggable = true;
    newDiv.id = 'record-2-'+index;
    newDiv.className = 'record';
    newDiv2.className = 'record';
    newDiv2.id = 'record-4-'+index;
    newDiv2.draggable = true;
    newDiv2.innerHTML=array[index];
    div4.appendChild(newDiv); // append to div
    div2.appendChild(newDiv2); // append to div
    newDiv.addEventListener("dragstart", handleDragStart);
    newDiv2.addEventListener("dragstart", handleDragStart);
}

How I can achive same functionality without having two separate variable newDiv, newDiv2.

Shubham Batra
  • 2,357
  • 5
  • 29
  • 48

2 Answers2

0

You could clone the div and add that by using cloneNode(), so you are adding two separate divs, not the one same one.

var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
    var newDiv=document.createElement("div"); //create a new div
    newDiv.innerHTML=array[index];
    newDiv.draggable = true;
    newDiv.id = 'record-2-'+index;
    newDiv.className = 'record';

    div4.appendChild(newDiv); // append to div
    newDiv = newDiv.cloneNode(false); // clone the div
    newDiv.id = 'record-4-'+index; // change its id property
    div2.appendChild(newDiv); // append to div
    newDiv.addEventListener("dragstart", handleDragStart);
    newDiv2.addEventListener("dragstart", handleDragStart);
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

You could create a function wich return or adds the div to a passed div:

//Required..
function handleDragStart(){};

//Created and append divs
function addDivTo(div, html, id){
    //appendChild() returns the input
    var newDiv = div.appendChild(document.createElement("div")); //create a new div
    newDiv.id = id;
    newDiv.innerHTML = html;
    newDiv.draggable = true;
    newDiv.className = 'record';
    newDiv.addEventListener("dragstart", handleDragStart)
  }

//Some array used below
var array = ['123', '456', '789', 'cucubau'];

var div4 = document.getElementById('div4'); // get the div element
var div2 = document.getElementById('div2'); // create a new div

for (var index = 0; index < array.length; index++) {
  addDivTo(div4, array[index], 'record4-' + index);
  addDivTo(div2, array[index], 'record2-' + index)
}
<div id = 'div4'></div>
<div id = 'div2'></div>