How to change style of nth-child using jQuery?

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

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

How to make HTML form interactive and using CSS?CSSWhat is the difference between float and double?MiscHow to Remove PHP File Extensions From Your Website URLs?PHPLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQL12 URLSearchParams methods in JavaScriptJavaScriptAccessing and Setting features of JavaScript ObjectsJavaScriptWordPress: How to find all posts from a custom post type with specific custom field?WordPressWhat’s a Log File and What are Log File Monitors?MiscCreate a responsive pricing table using simple HTML and CSSCSSWhat is the difference between let and var in Swift?SwiftHere’s what we can do with PHP date() functionPHPHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHP