In jQuery, :eq() and :nth-child() are both selectors that can be used to target specific elements within a set, but they have key differences in their functionality.
The :eq() selector selects an element with a specific index within the set of matched elements. The index is zero-based, meaning that :eq(0) selects the first element, :eq(1) selects the second, and so on.
The :nth-child() selector, on the other hand, selects elements based on their position within their parent container, not just within the set of matched elements. It uses an expression like :nth-child(an+b) where a and b are integers. It selects every element that is the an+b- th child of its parent.
Description | :eq() | :nth-child() |
---|---|---|
Scope of Selection | operates within the set of matched elements, allowing you to select elements by their index within that set. | :nth-child() operates on the parent-child relationship, selecting elements based on their position within their parent container. |
Indexing | uses zero-based indexing, where :eq(0) refers to the first element | uses a formula (an+b) to calculate the position of an element relative to its siblings. |
Usage | is often used when you have a specific index in mind within a set of elements. | is more versatile and can be used to select elements based on a variety of patterns within their parent containers. |
<html> <head> <title>DOM Query</title> <style> li{color:black;} .color{color:red;} </style> </head> <body> <h3>Nth Child With eq</h3> <ul class='list'> <li>Graphic Designing</li> <li>Web Designing</li> <li>Programming</li> <li> <ul> <li>C Program</li> <li>C++ Program</li> <li>Java</li> <li>C#</li> </ul> </li> </ul> <script src="js/jquery.js"></script> <script> $("document").ready(function(){ //$('ul.list').children('li:nth-child(2)').text('This is Nth Child by CSS jQuery'); $('ul.list').children('li').eq(1).text('This is Nth Child by EQ jQuery'); }); </script> </body> </html>
Choose :eq() when you want to select elements based on their index within a specific set, and use :nth-child() when you want to select elements based on their position within their parent containers, allowing for more flexible and complex selections.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions