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


To change the first and last elements of a list use the eq() method.

Example

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

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 
 $(document).ready(function(){
   $("#list li:eq(2)").after($("#list li:eq(0)"));
 });
   
</script>
</head>
<body>
<p>This year's ranking:</p>
<ul>
  <li>India</li>
  <li>US</li>
  <li>UK</li>
</ul>

<p>Last year's ranking:</p>

<ul id="list">
  <li>India</li>
  <li>US</li>
  <li>UK</li>
</ul>

</body>
</html>

Updated on: 18-Dec-2019

560 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements