Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending the same element to different elements

Tags:

javascript

dom

I have two empty select fields, I want to iterate once over some array, create an option element in each iteration, and append it to both select fields. The problem is that only the last element gets the options, the first one remains empty:

HTML

<select class="form-control" id="typeCol">
</select>
<br>
<select class="form-control" id="diffCol">
</select>

JavaScript

let typeCol = document.getElementById('typeCol');
let diffCol = document.getElementById('diffCol');
for (let i in cols) {
    let opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = cols[i];
    typeCol.appendChild(opt);
    diffCol.appendChild(opt);
}

Adding another for loop and appending to the second select from there seems to work, but still - what's going on?

like image 287
user99999 Avatar asked Oct 26 '25 08:10

user99999


2 Answers

An element can only be inside one parent. If you use appendChild on an element that already has a parent, it's moved from the old parent to the new one.

You can use cloneNode to create a clone of the element instead:

diffCol.appendChild(opt.cloneNode(true));

Example:

let typeCol = document.getElementById('typeCol');
let diffCol = document.getElementById('diffCol');
let cols = ["one", "two", "three"];
for (let i in cols) {
    let opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = cols[i];
    typeCol.appendChild(opt);
    diffCol.appendChild(opt.cloneNode(true));
}
<select class="form-control" id="typeCol">
</select>
<br>
<select class="form-control" id="diffCol">
</select>
like image 79
T.J. Crowder Avatar answered Oct 28 '25 21:10

T.J. Crowder


You can't append same element, However you can use cloneNode() method to create a clone then append it.

typeCol.appendChild(opt);
diffCol.appendChild(opt.cloneNode(true));
like image 35
Satpal Avatar answered Oct 28 '25 21:10

Satpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!