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.


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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
Canvas Drawing in HTML5HTMLHow to use $INSERT command in Envision Basic?Envision BasicWhen you don’t want to @forward every member in SCSS (Sass)SCSSHow to change CSS with JavaScript?CSSHow to Use SQL MAX() Function with Dates?SQL/MySQLHow to compress images with gulp in WordPress?WordPressList of all Pseudo Elements in CSSCSSThe basics of CSS Box modelCSSHow to select an element using its ID without the high specificity of the ID selector?CSSHow to change value of a span tag using a reference from another div using jQuery?jQuery12 URLSearchParams methods in JavaScriptJavaScriptHow to Recognize an Array in JavaScript?JavaScript