---
title: "Use of first() and last() methods in jQuery"  
description: "Use of first() and last() methods in jQuery"  
author: "Ethan Karla"  
published: 2021-07-28  
updated: 2023-06-14  
canonical: https://www.mindstick.com/forum/156658/use-of-first-and-last-methods-in-jquery  
category: "jquery"  
tags: ["jquery"]  
reading_time: 2 minutes  

---

# Use of first() and last() methods in jQuery

What is the use of first() and last() [methods in jQuery](https://www.mindstick.com/forum/159116/explain-the-difference-between-fadeout-and-hide-methods-in-jquery)?\

## Replies

### Reply by Aryan Kumar

The first() and last() [methods](https://www.mindstick.com/articles/13060/runny-nose-remedy-methods-that-work-best) in jQuery are used to select the first and last elements in a set of elements, respectively. They are both chainable methods, which means that you can call other jQuery methods on the returned object.

The first() method takes no arguments, while the last() method can take an optional argument that specifies the index of the last element to select. If no argument is specified, the last() method will select the last element in the set.

Here are some examples of how to use the first() and last() methods:

Code snippet

```plaintext
// Select the first element in the set
$('.my-class').first();

// Select the last element in the set
$('.my-class').last();

// Select the second-to-last element in the set
$('.my-class').last(2);
```

The first() and last() methods can be used to perform a variety of tasks, such as:

- Selecting the first or last element in a set of elements
- Adding or removing an event handler from the first or last element in a set of elements
- Changing the style of the first or last element in a set of elements
- Getting or setting the value of an attribute on the first or last element in a set of elements

The first() and last() methods are a powerful tool that can be used to easily select the first or last element in a set of elements.

Here are some additional examples of how the first() and last() methods can be used:

Code snippet

```plaintext
// Change the color of the first element in the set to red
$('.my-class').first().css('color', 'red');

// Add an event handler to the last element in the set to prevent it from being deleted
$('.my-class').last().on('click', function() {
  return false;
});

// Get the value of the href attribute on the last element in the set
var href = $('.my-class').last().attr('href');
```


---

Original Source: https://www.mindstick.com/forum/156658/use-of-first-and-last-methods-in-jquery

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
