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