How to Get the First nth and Last Element in jQuery

Let’s go through some ways to retrieve any element in a set of DOM elements in jQuery:

  • eq(index) returns the element as selector at the specified index.
  • first() method constructs a new jQuery object from the first element in a jQuery object that represents a set of DOM elements.
  • last() method constructs a new jQuery object from the last element in a jQuery object that represents a set of DOM elements.

Consider a list like this:

<ul class="sidebar-list">
	<li>jQuery Plugins</li>
	<li>Unity Assets</li>
	<li>Android Libraries</li>
	<li>>Flutter Plugins</li>
	<li>Developer Tools</li>
	<li>BaaS</li>
	<li>Wordpress Plugins</li>
	<li>Wordpress Themes</li>
</ul>

Get the first element

jQuery('ul li').first().text();
jQuery('ul li').eq(0).css( 'background-color', 'green' );

Get the nth element

var nthElement = jQuery('ul li').eq(n);
console.log(nthElement.text())

Get the last element

jQuery('ul li').last().attr('style', 'color: red;');
jQuery('ul li').eq(jQuery('ul li').length).css( 'color', 'blue' );

Leave a Comment

Your email address will not be published. Required fields are marked *

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close