Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first and last element with particular class using jQuery

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> 
like image 395
tsusanka Avatar asked Nov 02 '10 22:11

tsusanka


People also ask

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do you select the first element with the selector statement?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

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. }); 
like image 76
Stephen Avatar answered Oct 11 '22 11:10

Stephen