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

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

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 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