tags:

views:

191

answers:

4

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 for the current item.

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

Thanks

Chris

+10  A: 
$('.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.

Sonny Boy
just to clarify $('.ICS_Picture:lt(' + n + ')').addClass('hideme');
Mickel
Hum, I thought that he wanted to apply the class to all but the N first items ?
Wookai
or `$('.ICS_Picture:gt(n)').addClass('hideme');` for items after a certain number.
czarchaic
I think this si the most elegant response so far, but he needs the :gt version.
Elzo Valugi
A: 

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.

Guillaume Flandre
Please justify the downvote. this solution works, even though Sunny Boy's one is better.
Guillaume Flandre
funny how you "optimize" the callback, but don't mind querying the dom over and over. -1
just somebody
No -1 from me, but "just somebody" is correct. For each iteration you're hitting the DOM to find the correct element. Better to get them all at once (outside your loop) and then loop through them.
Sonny Boy
Yep that's true, I edited my answer.
Guillaume Flandre
minor recommendation: `for (var i=0, j=$ICSPictures.length; i < j; i++)` P.S., ... what's so bad about `each`?
Funka
You should check out that Google Talk: http://www.youtube.com/watch?v=mHtdZgou0qU
Guillaume Flandre
A: 

You can do that with the gt() selector :

var toSkip = 4;
$('.ICS_Picture:gt(' + (toSkip - 1) + ')').addClass("hideme");
Wookai
-1: `$('.ICS_Picture').each(function (count) ...` if you insist on `each`, but it's unnecessary anyway
just somebody
Yep, I was just referring to his code, but I'll just remove it and keep the gt version.
Wookai
+2  A: 
$('.ICS_Picture:gt(4)').addClass('hideeme');
Yuriy Faktorovich