jQuery :eq() Selector
Purpose: The :eq() selector is used to select the element at a specified index within a matched set of elements. Indexing: The index is zero-based, meaning the first element has an index of 0. Usage: It is useful when you need to target a specific element out of a group of matched elements based on its position. Return Value: Returns a jQuery object containing the element at the specified index.
Syntax
Following is the syntax of jQuery :eq() Selector −
$(":eq(index)")
Parameters
Here is the description of the above syntax −
- index: The zero-based index of the element to select.
Example 1
In the following example, we are using the jQuery :eq() Selector to select the paragraph element with index "2" −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p:eq(2)").css("background-color", "yellow");
});
</script>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
</html>
After executing the above program, the paragraph element with index "2" will be highlighted with yellow background color.
Example 2
In this example, we are selecting the list item with index "1" −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("li:eq(1)").css("background-color", "yellow");
});
</script>
</head>
<body>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
</ul>
</body>
</html>
After executing the above program, the list item with index "1" will be highlighted with yellow background color.
Example 3
Here, we are selecting the <div> element with index "3" −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Select and hide the fourth div element (index 3)
$("div:eq(3)").hide();
});
</script>
</head>
<body>
<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>
<div>Div 4</div>
</body>
</html>
After executing the above program, the selected element will be highlighted with yellow background color.
jquery_ref_selectors.htm
Advertisements