I want to add a new option onto all the existing dropdown menus in my page. I get all the menus using querySelectorAll and loop through each and add the option.
// creating my option
let opt;
opt = document.createElement('option');
opt.value = 10;
opt.text = 'hello';
// looping and adding the option
document.querySelectorAll('select').forEach(ele => {
ele.add(opt);
});
However the issue is only last dropdown list is getting this option added to it. All the preceding selects are not affected. Why? However if I create the new option within the loop as shown below, all the select lists get updated as intended
document.querySelectorAll('select').forEach(ele => {
let opt;
opt = document.createElement('option');
opt.value = 10;
opt.text = 'hello';
ele.add(opt);
});
Why is it like this? Please help.