Reputation: 3688
I have some grouped <li>
tags as follows in my webpage.
<ul id="dg">
<!-- group-1 -->
<li data-group="one">....</li>
<li data-group="one">....</li>
<li data-group="one">....</li>
<li data-group="one">....</li>
<!-- group-2 -->
<li data-group="two">....</li>
<li data-group="two">....</li>
<!-- group-3 -->
<li data-group="three">....</li>
<!-- group-4 -->
<li data-group="four">....</li>
<li data-group="four">....</li>
<li data-group="four">....</li>
</ul>
Likewise I have around 20(Its dynamic) groups of <li>
tags which categorized using the 'data-group'. Each category having different amount of <li>
tags.
What I want to do is, I want to select every 4th group(data-group) and add a CSS class named 'edge' to all of its <li>
tags using jQuery or Add a CSS property using nth.
Please help me fix this.
Thanks and Regards
Upvotes: 1
Views: 572
Reputation: 14025
UPDATE
You can't simply use a selector. You must loop through all your li
and deduce if they are belonging to the groups you want
var currentGroup = ""; //Name of the group currently checked
var counter = 0; //Number of group found
//Loop through the items
$('#dg li').each(function(){
//Check if we are checking a new group
if(currentGroup != $(this).attr('data-group'))
{
//If yes, save the name of the new group
currentGroup = $(this).attr('data-group');
//And increment the number of group found
counter++;
}
//If the number of the group is a multiple of 4, add the class you want
if((counter % 4) == 0)
$(this).addClass('edge');
});
Upvotes: 1
Reputation: 5213
So something like:
$('li[data-group="four"]').each(function(){
$(this).addClass('edge');
});
Is that what you mean?
So more like:
function processItems(items){
items.each(function(){
$(this).addClass('edge');
});
}
processItems($('li[data-group="four"]'));
processItems($('li[data-group="eight"]'));
processItems($('li[data-group="twelve"]'));
I am unaware of the performance gain or doing something like this, but looping through each and every li
item could be bad AND slow depending on the number of them in your list. Not saying what I have here is the BEST way, but if you have hundreds of li items, your loop could run slowly.
Upvotes: 1