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>
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.
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).
$() = 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.
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. });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With