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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
Number Properties in JavaScriptJavaScriptSolution for “Yarn build: Failed because of a stylelint error”WordPressValues and Types Basics in JavaScriptJavaScriptSome Useful Operators in The SQL WHERE ClauseSQL/MySQLthe box-sizing property in CSSCSSThe Difference Between Arrays and Objects in JavaScriptJavaScriptHow to verify your domain in Google Console with a TXT record?MiscellaneousWhat is PostgreSQL? How similar or different it is from SQL?PostgresUNION and UNION ALL in PostgresPostgresWhat are Stored Procedures for SQL Server?SQL/MySQLHow to implement NSNumberFormatter in Swift for currency?SwiftWhere is the PHP log file located on Mac OS?PHP