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

133
Views
jquery loop id for div

I have bootstrap accordion and I'm tryin to get ID and HREF for every accordion in jquery. here is my code

$('.room-loop').each(function(id){
    $('.room-loop-a').attr("href", '#'+(id));
    $('.room-loop-body').attr("id", id)
    console.log(id)
  });

but id and href for every class named "room-loop-a" and "room-loop-body" is 3. I tried many methods like importing variable ID and in loop make it id+=1, but in attr dont work none of em. any ideas?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You most likely need to use .find() depending on your html.

$('.room-loop').each(function(id) {
  $(this).find('.room-loop-a').attr("href", '#room' + (id));
  $(this).find('.room-loop-body').attr("id", "room" + id)
  console.log(id)
});

Problem is that this $('.room-loop-a').attr("href", '#'+(id)); will set the same href to all elements with the class room-loop-a

Also please note it's not recommended that your id starts with a number, so I've added room in front, but you can change that to your liking.

Demo

$('.room-loop').each(function(id) {
  $(this).find('.room-loop-a').attr("href", '#room' + (id));
  $(this).find('.room-loop-body').attr("id", "room" + id)
  console.log(id)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="room-loop">
  <a href="" class="room-loop-a">room-loop-a</a>
  <div class="room-loop-body">
    room-loop-body
  </div>
</div>

<div class="room-loop">
  <a href="" class="room-loop-a">room-loop-a</a>
  <div class="room-loop-body">
    room-loop-body
  </div>
</div>

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!