admin管理员组

文章数量:1401491

I am using jQuery to count divs and would like to have a class added once it counts 20. ie: divs 1-20 are class="box" and divs 21 + are class="box new"

This is what I have but it adds the "new" class to all the divs.

$(function() { 
    var divCount = $("#content").children(".box").length; 

    if (divCount > 20) { 
        $(".box").addClass("new"); 
    } 
});

I am using jQuery to count divs and would like to have a class added once it counts 20. ie: divs 1-20 are class="box" and divs 21 + are class="box new"

This is what I have but it adds the "new" class to all the divs.

$(function() { 
    var divCount = $("#content").children(".box").length; 

    if (divCount > 20) { 
        $(".box").addClass("new"); 
    } 
});
Share Improve this question asked Sep 6, 2013 at 18:20 awsmawsm 951 gold badge4 silver badges9 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 7
$(".box:gt(20)").addClass("new"); 

Just want to point out that you can do this with just CSS using nth-child. Of course, if you're using the class for targeting you still may want to go the jQuery route:

div.box:nth-child(n+21) {
    ... new styles go here   
}

See more here: http://css-tricks./useful-nth-child-recipies/

Something like this should work:

var i = 0;
$("#content").children(".box").each(function(i, k) {
   if(++i > 20) $(k).addClass("new");
});

or

$("#content").children(".box").each(function(i, k) {
   if($(k).is(":gt(20)")) $(k).addClass("new");
});

Take into account that your code says as follows: If there are more than 20 boxes, add class 'new' to all the divs with class 'box'. And so, all the boxes are selected.

In this case, I remed using the :gt() selector: gt-selector - jQuery

Therefore:

$(function() { 
    $(".box:gt(20)").addClass("new"); 
});

You can use this cheatsheet if you're not sure which selector to use: Oscar Otero jQuery Cheatsheet

Your code:

if (divCount > 20)

is actually checking a condition for truthfulness and adding a class "new" to all elements that have the class .box because the condition passes the test when you have more than 20 divs.

What you want to do is loop through the elements and check for truthfulness of your condition inside that, applying the new class to the current element if it's index is above 20 - 1 (counting starts at zero, so your element with an index of 19 will be your 20th element).

$(function() {
    $.each($("#content").children(".box"), function(index, value){
        if ( index - 1 > 20 ) {
            $(this).addClass(".new");
        }
    });
});

本文标签: javascriptjQuery count divs and add class after 20Stack Overflow