Yogesh Chauhan's Blog

How to change style of nth-child using jQuery?

in jQuery on March 7, 2021

jQuery has :nth-child() Selector that can be used to select all nth-childs of their parent and apply the style to those elements.

We can pass similar parameters as we pass in CSS. Such as the index of the child element child (starting with 1) or the string odd/even, or even an equation for eg. :nth-child(even), :nth-child(2n).

jQuery strictly implements :nth- selectors directly from the CSS specification, so the value of n is “1-indexed”, which means that the counting of child elements starts at 1.

Other jQuery methods like .first() or .eq() follows “0-indexed” counting that is derived from JavaScript.

This is how we can select the first element:


...
$( "li:nth-child(1)");
...

With :nth-child(n), all children are counted and the specified element is selected only if it matches the selector attached to the pseudo-class.

Examples:

Find the second li in each matched ul and change the color.

Credit: jQuery Docs


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
ALTER DATABASE in PostgreSQLPostgres4 different Ways to Get JavaScript OutputJavaScriptHow to remove trailing characters from a string using JavaScript?JavaScriptHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPCustom Post Type Template Files in WordPressWordPressAdvanced Array Methods in JavaScript (with examples)JavaScript3 Ways we can create URLSearchParams Objects in JavaScriptJavaScriptHow to insert Bootstrap 4 in Angular 9 app?AngularWhat is Hoisting in JavaScript?JavaScriptHow to create a circle that follows a cursor using JavaScript and CSS?CSSperspective property in CSSCSSHow to change style of nth-child using jQuery?jQuery