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

238
Visualizações
Why each() loop changes only the last element?

I have problem with iteration in jquery that i dont understand. I grab all select2 elements having given name and try to append new option:

var newOption = new Option(model.nazwa, model.id, false, false);

$('select[name="grupa_cechy_id"]').each(function () {
    $(this).append(newOption).trigger('change');
    //check the loop works
    let idx = $(this).attr('id');
    console.log(idx);
});

The loop works but only last select2 element from the loop gets new option. How to fix that?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

DOM elements can have only a single parent. What you're actually doing, is attempting to append the element to multiple parents, which effectively just moves it around in the DOM. Thus, it will continuously be moved until the last element in the loop, when it is no longer appended to any other elements.

You should refactor your code, and create a new option each time the loop is iterated, as follows:

$('select[name="grupa_cechy_id"]').each(function () {
    const newOption = new Option(model.nazwa, model.id, false, false);
    $(this).append(newOption).trigger('change');
});
about 4 years ago · Juan Pablo Isaza 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