How to get an element with a specific index in jQuery With Example

In this post, we are going to discuss how to get an element with a specific index. jQuery API provides eq() method for this operation.

jQuery eq() method

The jQuery eq() method is used to get an element with a specific index of the selected HTML element. You can give either positive or negative integer value as index. The index of the first element of the matched element is 0. If we use selector.eq(-1), it will return the last element and selector.eq(0) will return the first element in the matched set of elements.

Here is the general syntax for using jQuery eq() method:

index could be any positive or negative integer.

jQuery eq() example

Following example demonstrates the jQuery eq() method usage.


<!doctype html>
<html>
<head>
<title>jQuery Traversing eq</title>
<style>
    .highlight{
       background: yellow;
     }
    .highlight1{
       background: green;
     }
    div{
      display: block;
      border: 3px solid black;
      color: black;
      padding: 5px;
      margin: 25px;
      width:250px;
     }
</style>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<h2>jQuery eq() demo</h2>
<div>My index is 0, also -6 from last</div>
<div>My index is 1, also -5 from last</div>
<div>My index is 2, also -4 from last</div>
<div>My index is 3, also -3 from last</div>
<div>My index is 4, also -2 from last</div>
<div>My index is 5, also -1 from last</div>
<script>
$( "div" ).eq( "1" ).addClass("highlight");
$( "div" ).eq( "-6" ).addClass("highlight1");
</script>
</body>
</html>

In this example, we can see the use of jQuery eq() method. The $("div").eq(1) will return the second div element and changes the color to yellow. Similarly the elements are searched when index is negative, so -6 will return the first div element in this html page. Below image shows the output produced by above HTML page.

jquery-eq-example-413x450

That’s all for now. We will discuss some more traversing techniques in the coming posts.

By admin

Leave a Reply

%d bloggers like this: