Reputation: 357
I have a set of divs with the same class. I need to give each one an individual ID. And then apply that ID to the href of a link.
Here is the HTMl:
<div class="person-promo">
<a href="***#ID-OF-SIBLING-DIV***" class="action">> Read More</a>
<div class="hide">
<div id="***NUMBER-GOES-HERE***" class="person-details">
<!-- -->
</div>
</div>
</div><!-- Person Promo -->
Each anchor needs to link to its sibling Div, if that makes sense.
I have been hunting around various sites, and the Jquery library for a few hours, but have had no luck. Just hoping for a bit help.
Thanks for everyone's help by the way. It's good to know SOME fellow developers will help each other out during difficulties. It is a great community on here.
Upvotes: 1
Views: 1122
Reputation: 26143
Using counters seems a bit overkill, since there's an inbuilt index number available anyway...
$(".person-promo").each(function(Index) {
$(this).find("action").attr("href", "#person" +Index);
$(this).find(".person-details").attr("id", "person" + Index);
});
Upvotes: 1
Reputation: 4517
var id = 0;
$('a').each(function() {
$(this).attr('href','#anchor' + id);
$(this).find('div').attr('id','anchor' + id);
id++;
});
Upvotes: 0
Reputation: 4084
I guess you could do:
var i = 0;
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$('.person-promo').each(function(){
var theID = str.charAt(i);
i++;
$(this).find('a.action').attr("href", "#"+theID);
$(this).find('.person-details').attr("id", theID);
});
Don't forget, you should never use integers as an ID
Upvotes: 0
Reputation: 10305
You could also bind a click event to the <a>
elements to find the specific div like this
$('a.action').click(function(e) {
e.preventDefault();
var div_details = $(this).parent().find('.person-details');
// use div_details to show or hide etc..
})
Upvotes: -1
Reputation: 9027
Easy enough:
// Loop through the divs
$(".person-promo .person-details").each(function(i) {
// Store an id with format "uniqueId_{index}" in a variable.
var id = "uniqueId_" + i;
// Give the ID to the div
$(this).attr("id", id);
// Give it to the sibling link
$(this).siblings("a").attr("href", "#" + id);
});
That said, you should probably generate all this server-side.
Upvotes: 2