Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda