How to change first and last elements of a list using jQuery?

To change the first and last elements of a list, you can use jQuery's eq() method along with first() and last() methods. The eq() method allows you to select elements by their index position, where the first element has an index of 0.

Methods for Selecting First and Last Elements

jQuery provides several methods to target the first and last elements ?

  • :first or first() ? Selects the first element
  • :last or last() ? Selects the last element
  • :eq(0) ? Selects the first element (index-based)
  • :eq(-1) ? Selects the last element using negative indexing

Example

You can try to run the following code to change first and last elements of a list using jQuery ?

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         // Change text content of first and last elements
         $("#list li:first").text("Australia");
         $("#list li:last").text("Canada");
         
         // Alternative method using eq()
         $("#list2 li:eq(0)").text("Germany");
         $("#list2 li:eq(-1)").text("France");
      });
   </script>
</head>
<body>
   <p>Original ranking:</p>
   <ul id="list">
      <li>India</li>
      <li>US</li>
      <li>UK</li>
   </ul>

   <p>Another list:</p>
   <ul id="list2">
      <li>Japan</li>
      <li>Brazil</li>
      <li>Italy</li>
   </ul>
</body>
</html>

The output will show the lists with modified first and last elements ?

Original ranking:
? Australia
? US
? Canada

Another list:
? Germany
? Brazil
? France

Conclusion

Using jQuery's eq(), first(), and last() methods, you can easily target and modify the first and last elements of any list. This approach is useful for dynamic content updates and list manipulations.

Updated on: 2026-03-13T18:23:38+05:30

845 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements