28

I have a list of spans with particular class "place" and some of them have class "activated". Is there a way to select the first item with class "activated" and the last?

<span class="place" onclick="activate();">1</span>
<span class="place" onclick="activate();">2</span>
<span class="place activated" onclick="activate()">3</span>
<span class="place activated" onclick="activate();">4</span>
<span class="place activated" onclick="activate();">5</span>
<span class="place activated" onclick="activate();">6</span>
<span class="place" onclick="activate();">7</span>
jball
  • 24,270
  • 9
  • 68
  • 91
tsusanka
  • 4,631
  • 6
  • 33
  • 42

4 Answers4

39
var firstspan = $('span.activated:first'),
    lastspan = $('span.activated:last');

By the way, if you're using jQuery, what's with all the inline click events?

You could add some code like so:

$('span.place').click(function() {
    activate(); // you can add `this` as a parameter
                // to activate if you need scope.
});
Stephen
  • 18,491
  • 9
  • 59
  • 98
  • 1
    I have a lot of those spans and in each one of them theres this activate function with different atributes, so I think its better that way. Thanks for great reply – tsusanka Nov 02 '10 at 22:43
14
var places = $('span.place.activated');

var first = places.first(),
    last  = places.last();

Explanation: The span.places.activated selector will get all <span>s with both "place" and "activated" classes. Then the first() and last() methods will return the first and last items of that set. This is preferable to using the :first and :last pseudoselectors because selection is expensive and this way we only do selection once and then rely on (cheap) array operations to get the first and last elements.

Jordan Running
  • 97,653
  • 15
  • 175
  • 173
1

If you take care about performance, than better use $('span.place.activated') instead $('.activated:first'). But, in this case, the second variant correct too.

Vasyl
  • 1,244
  • 15
  • 26
0
var first = $('.activated:first');
var last = $('.activated:last');
Aaron Hathaway
  • 4,180
  • 1
  • 17
  • 17