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 add Read More Read Less Button using JavaScript? #2 How to check if radio button is checked or not using JavaScript? #3 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #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
How to compress images with gulp in WordPress?WordPressColleague UI Basics: The Search AreaColleagueWhat’s the difference between variables in CSS and SCSS (Sass)?CSSAn Introduction to wp-config file in WordPressWordPressHow states work in React?ReactHow to create a simple text and image slider using CSS and JavaScript?CSSHow to Skip or Exclude a Specific URL or File From .htaccess Rewrite Rule?PHPWhat is the best way to add JavaScript Code into HTML?HTMLHow does Binding work in JavaScript?JavaScriptCreate a menu with a curtain falling animation using CSS and JavaScriptCSSHow to add a Bar Chart in Angular App?AngularThe :last-of-type selectorCSS