Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access element with nth index in jQuery?
To access element with nth index from an HTML page, use the jQuery eq() method. It is used to access the index of an element in jQuery. The eq() method refers to the position of the element.
The eq() method accepts a zero-based index parameter, meaning the first element is at index 0, the second element is at index 1, and so on. This method returns a jQuery object containing only the element at the specified index position.
Syntax
The basic syntax of the eq() method is ?
$(selector).eq(index)
Where index is the zero-based position of the element you want to select.
Example
You can try to run the following code to access element with nth index in jQuery. Here, element with 2nd index is considered ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('ul li').eq(2).css({'background-color':'#E6B16A'});
});
</script>
</head>
<body>
<ul>
<li>India</li>
<li>US</li>
<li>UK</li>
<li>Australia</li>
</ul>
</body>
</html>
The output of the above code is ?
The third list item "UK" will have a light brown background color (#E6B16A) applied to it, while the other list items remain with their default styling.
In this example, $('ul li').eq(2) selects the third list item (index 2) from the unordered list and applies a background color to it using the CSS method.
Conclusion
The jQuery eq() method provides an efficient way to access elements by their index position within a collection. Remember that indexing starts from 0, making it essential to count positions accordingly when targeting specific elements.
