Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!