YogeshChauhan . com

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Arguments in @mixin rules in SCSS (Sass)SCSSHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresSelect statement in Postgres with examplesPostgresHow to check if the element exists using JavaScript and jQuery?JavaScriptHow to Recognize an Array in JavaScript?JavaScriptHow to check if the page is the home page in WordPress?WordPressCREATE TABLE Examples in PostgreSQLPostgresThe 8 Golden Rules of Programming I Have Learned in My CareerMiscThe basics of CSS Box modelCSSHow to remove border from :visited image, link or button?CSSHow to import MySQL small sample database into phpMySQL?SQL/MySQLSelector Lists and Combinators in SCSS (Sass)SCSS