Home > Blockchain >  Issue with adding a new option to all select elements in javascript by looping
Issue with adding a new option to all select elements in javascript by looping

Time:09-27

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.

CodePudding user response:

Although This question already has answers here (that you need a new element for each add):

forEach loop only creating last DOM element
Why each() loop changes only the last element?
appendChild in for loop only adds 1 child
Javascript Loop: inserting element only working on last iteration

I will post my suggestion since it is simpler than the others

let opt = new Option('10', 'hello');
const sels = document.querySelectorAll("select")
 .forEach(s => s.appendChild(opt.cloneNode(true)));
<select name="one">
  <option value="1">One</option>
</select>
<select name="two">
  <option value="1">Two</option>
</select>
<select name="three">
  <option value="1">Three</option>
</select>
<select name="four">
  <option value="1">Four</option>
</select>

CodePudding user response:

Your code did not work because document.createElement("option") was called only once and subsequently the same element was reassigned to a series of select elements. After the first time the same option was simply moved to the next select and not copied.

In contrast to that the following script makes use of the element method .insertAdjacentHTML() which creates new elements on the fly and adds them at the specified point.

document.querySelector("button").onclick=ev=>{
 document.querySelectorAll("select").forEach(s=>s.insertAdjacentHTML("beforeend",'<option value="10">hello</option>'));
}
<select name="one"><option value="1">Start</option></select>
<select name="two"><option value="1">as you</option></select>
<select name="three"><option value="1">mean to</option></select>
<select name="four"><option value="1">go on!</option></select>
<br><button>add an option</button>

  • Related