开发者

JQuery - Go through every instance of div with class and add class to the first n items

开发者 https://www.devze.com 2022-12-14 03:48 出处:网络
I have some boxes <div class=\'ICS_Picture\'> Text </div> <div class=\'ICS_Picture\'> Text

I have some boxes

<div class='ICS_Picture'>
Text
</div>
<div class='ICS_Picture'>
Text
</div>
<div class='ICS_Picture'>
Text
</div>
<div class='ICS_Picture'>
Text
</div>

I want jquery to add a class to all items after the first n number of items..

I have some similar code that does it for tr's but cannot get the syntax right f开发者_如何学编程or the current item.

$('.ICS_Picture').each(function(){
   $(this).addClass("hideme");
});

Thanks

Chris


$('.ICS_Picture:lt(n)').addClass('hideme');

With n being the number of elements to which you wish to apply the class. So if you want to apply it to the first four elements, n = 4.

EDIT--

I just reread the question and OP is looking to apply the styles to items AFTER a certain number. In that case, please use this instead:

$('.ICS_Picture:gt(n-1').addClass('hideme');

Please note the n-1 because the indexing is zero-based and so if you want to start applying the styles after the 4th element you'll need to ensure that the value you provide is 3. Obviously, standard concatenation rules will apply if you plan for n to be a dynamic value rather than hard-coded.


$('.ICS_Picture:gt(4)').addClass('hideeme');


You can do that with the gt() selector :

var toSkip = 4;
$('.ICS_Picture:gt(' + (toSkip - 1) + ')').addClass("hideme");


First of all, each is not the most optimized way to iterate through a jquery object.

What you can do to achieve what you want is:

    var $ICSPictures = $('.ICS_Picture');
    for (var i=0;i<$ICSPictures.length;i++){
      if(i>=myLimit)
        $ICSPictures.eq(i).addClass("hideme");
    }

myLimit being the number n you're refering to in your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号