Cris
Cris

Reputation: 4044

How to add a specific style to every fifth div element?

I want to add a border to every fifth element. The current code I have only select the first 5th element, not every one... what am I doing wrong?

jquery:

$(document).ready(function() {  

        $("#categories .cat:nth-child(5)").css({border: '1px solid red', color: '#ff0000'});

});

html:

<div id="categories">
    <div class="cat">   cat1    </div>
    <div class="cat">   cat2    </div>
    <div class="cat">   cat3    </div>
    <div class="cat"> cat4 </div>
    <div class="cat">   cat5    </div>
    <div class="cat">   cat6    </div>
    <div class="cat">   cat7    </div>
    <div class="cat">   cat8    </div>
    <div class="cat"> cat9 </div>
    <div class="cat">   cat10   </div>
</div>

Upvotes: 1

Views: 2327

Answers (3)

Wex
Wex

Reputation: 15695

Keep in mind that CSS3 selectors also allow you to do this without using javascript at all:

#categories:nth-child(5n) {
    color: #ff0000;
    border: 1px solid red; }

Note: This does not work in IE8 or earlier.

I wouldn't recommend using this on it's own, but rather in addition to a javascript solution (to ensure cross-browser compatibility). I just think that it might make sense for you to have both so browsers that are CSS3 compatible don't experience any sort of flicker when the Javascript is applied.

Upvotes: 2

user1107975
user1107975

Reputation:

didn't test it, but you could try something like this:

$(document).ready(function() {  
    var counter = 1;
    $("#categories").children().each(function(){ 
        if(counter%5==0)
            $(this).css({border: '1px solid red', color: '#ff0000'});
        counter++;
    });
});

Upvotes: 1

Purag
Purag

Reputation: 17061

Use this:

$("#categories .cat:nth-child(5n)")

Notice the 5n.

Upvotes: 7

Related Questions