Yogesh Chauhan's Blog

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

in jQuery on 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

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #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 replace HTML lists using CSS Counters?CSSWhat is XP (Extreme Programming) and When should it be used?MiscellaneousAdd animated hamburgers menu using Hamburgers collection on GitHubCSSKanban vs Scrum: The two frameworks of agile principlesMiscellaneousSelector Lists and Combinators in SCSS (Sass)SCSSWill SQL (Relational) Database become obsolete?SQL/MySQLSafe Practice to add Links to cross-origin destinationUI/UXHigher Order Functions in JavaScript with ExamplesJavaScriptHow to import a CSS file using PHP code and not HTML code?PHPHow to use [] (square brackets) function in Envision Basic?Envision BasicWhat is a Strict Requirement in PHP 7 Function Declarations?PHPWhat is React? Learn the basicsReact