Home > Blockchain >  Multiple appendChild calls in the same loop
Multiple appendChild calls in the same loop

Time:04-19

listCities.forEach(function(city){
   let option = document.createElement('option');
   option.value = city;
   listFrom.appendChild(option);
   listTo.appendChild(option);

});

I have an array and I want to add each string in it as options to two datalists (listFrom and listTo). The problem is that no matter the order I put them, only the last one of the list gets the options added to them.

Is there a way to do this in the same forEach loop or do I have to create two different loops that do exactly the same thing.

I'm just having trouble understanding the logic behind it.

CodePudding user response:

When you appendChild, you MOVE the element to the last mentioned container since the element only exists once in the DOM.

This is a LOT faster than creating an option, cloning it and appending it twice:

const listCities = ["Buenos Aires","Cordoba","Rosario","Mendoza","La Plata","Tucumán","Mar del Plata","Salta","Santa Fe","San Juan","Resistencia","Santiago del Estero","Corrientes","Neuquén","Posadas","San Salvador de Jujuy","Bahía Blanca","Paraná","Formosa","San Fernando del Valle de Catamarca","San Luis","La Rioja","Comodoro Rivadavia","Río Cuarto"], 
  listFrom = document.getElementById("from"), 
  listTo   = document.getElementById("to");

const options = listCities
  .map(city => `<option value="${city}">${city}</option>`)
  .join("");
listFrom.innerHTML  = options;
listTo.innerHTML    = options;
<select id="from"><option value="">From city</option></select> <select id="to"><option value="">To city</option></select>

CodePudding user response:

An element can only exist in one place. You need to make a clone of it

const listFrom = document.querySelector('#from');
const listTo = document.querySelector('#to');

listCities = ["a","b","c","d"];

listCities.forEach(function(city){
   let option = document.createElement('option');
   option.textContent = city;
   option.value = city;
   listFrom.appendChild(option);
   listTo.appendChild(option.cloneNode(true));
});
<label for="from">From:</label><select id="from"></select>
<label for="to">To:</label><select id="to"></select>

  • Related