tags:

views:

41

answers:

2

Hi, how do I use jquery to select the first and last item divs in the following snippet and apply a different additional class to each:

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

These will be somewhere on a web page. Thank you.

+5  A: 

Doesn't get much easier than:

$('.item:first').addClass('first');
$('.item:last').addClass('last');

You can also do it in a single command, if you want to save a few cycles:

$('.item')
    .eq(0).addClass('first').end()
    .eq(-1).addClass('last').end();
Kobi
+2  A: 
$('.item').filter(':first').addClass('first-class').end().filter(':last').addClass('last-class')

Try taking a look at jQuery's Selector API for other selectors.

aidilfbk
It was a good idea to show `.filter(':first, :last')` - it is possible that's what the OP (original poster) needs. Depends on how you interpret "a different additional class to each"
Kobi
FWIW, the page is large, and rounded borders are applied to those first and last divs: the user will see them become round once the page loads.
Adrian33
@Adrian33 - that's probably something you wanted so mention. You may also want to consider a CSS solution, it can work on all modern browsers, and will be visible from the start.
Kobi
@Kobi, true, thank you. I'll look into it.
Adrian33