Selecting the First or Last Element using jQuery
It’s very common that you might want to target the last and/or the first element matching a particular query selector (e.g. <li> elements). As you can see from the snippets below, jQuery makes such tasks quite easy.
A list of elements…
For the jQuery samples below, just assume we’re targeting an unordered list like the one below:
<ul> <li>First</li> <li>Second</li> <li>Third</li> </ul>
Selecting the first list element using jQuery
var firstListItem = $('li').first();
Selecting the last list element using jQuery
var lastListItem = $('li').last();
Setting a different styling for the first element
If your intention is to change the styling for the first or last element, then all you have to do is to add another method (through a concept called method chaining) like this:
$('li').first().css('color', 'red');
For more information, make sure to check out the jQuery documentation for the first() and last() methods.