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
5 Answers
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
版权声明:本文标题:javascript - jQuery count divs and add class after 20 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744301342a2599598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论