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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to convert an object from API to JSON array in Angular 9?AngularWhat is Prototypal Inheritance in JavaScript?JavaScriptHow to create ‘share on LinkedIn’ link using just HTML?HTMLHow to create a cross-browser smooth scrolling with jQuery?jQueryComponents and Props in ReactReact2 Ways we can create an Array in JavaScriptJavaScriptHow to get the first element with a class name xyz using JavaScript?JavaScriptHow to create a secure random number using JavaScript?JavaScriptWhat Is a Graph Database?MiscellaneousSubquery in PostgresPostgresHow to disable scrolling on html body on menu click using JavaScript?JavaScriptHow to install Gulp with WordPress?WordPress