Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

84
Visualizações
Issue with adding a new option to all select elements in javascript by looping

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.

almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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>

almost 4 years ago · Santiago Trujillo Relatório

0

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>

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda