problem trying to copy options from a select/option element to another void select in a DOMContentLoaded function

Viewed 24

im trying to copy the existing options from a select to another one after a DOMContentLoaded event and im having some strange behavior as a result:

<select id='select'>
    <option id='1'>option 1</option>
    <option id='2'>option 2</option>
    <option id='3'>option 3</option>
    <option id='4'>option 4</option>
</select>
<P>New option:</P>
<input type="text" name='new'>
<input type="button" value="crear" onclick='create()'></button>
<p>Edit</p>
<div id='editElement'>
<select name="selectEdit" id="selectEdit"></select>
<input type="text" id='edit'>
<input type="button" value="edit" >
<input type="button" value="remove" >
</div>
    <script>
   document.addEventListener('DOMContentLoaded', () => {
    select =  document.getElementById('select');
    selectEdit =  document.getElementById('selectEdit');
    for (let index = 0; index < select.length; index++) {
        selectEdit[index] = select[index];
        
    }   
    } );    
    </script>

some of the existing options from the 1st select are missing and in the second that im filling is incomplete too...i broke js?

1 Answers

It's because you are not copying them, you are moving them. To copy an element, you need use element.cloneNode(true)

selectEdit[index] = select[index].cloneNode(true);

And the reason why only some of them being moved is because when you move one element the select node list reduces by one, so in the next loop it skips one element.

Related