YogeshChauhan.com

How to change style of all direct children of an element using jQuery?

March 7, 2021

We can use the children() method to get all direct children of the specified element.

The .children() method searches through the children elements in the DOM and constructs a new jQuery object from the elements that are matched.

The .children() method only travels a single level in the DOM tree.

If you want to traverse multiple levels and select all descendant elements (we call them grandchildren!) in the DOM tree then use the .find() method.

The .children() method doesn’t return text nodes.

We need use the .contents() method to get all children including text and comment nodes.

We can also optionally use selectors to filter out the elements. We can pass selectors using the $() function.

A quick example of jQuery .children() method

This example selects all direct children of ul with level-2 class.

Change style for all direct elements with a class using jQuery .children() method

Credit: jQuery Docs

dreamhost

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

10 Usability Blunders to AvoidUI/UXFETCH clause in PostgreSQLPostgresHow to display and animate image on scroll using JavaScript?JavaScriptThe Drupal flowDrupalArray destructuring and Object destructuring in JavaScriptJavaScriptHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresSolution for the error Commit failed – exit code 1 received in Desktop GithubMiscHow to Remove PHP File Extensions From Your Website URLs?PHPHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPIN Operator in PostgreSQLPostgresWordPress: How to loop through a repeater field in ACF?WordPressGive buttons accessible namesUI/UX