.children() JQ Home  <<  Traversal  <<  .children()

Child elements retrieval.

Description

The .children() method is used to retrieve the children of each element within the matched set.

  • The .children() method will only travel a single level down the DOM tree, use the .find() method to travel down to grandchildren and beyond.
  • The .children() method does not return text or comment nodes, use the .contents() method to retrieve all children.

Syntax

Signature Description
.children()Retrieve the children of each element within the matched set.
.children( selector )Retrieve the children of each element within the matched set that match the specified selector.

Parameters

Parameter Description Type
selectorA string containing a CSS or custom jQuery selector to match elements against.Selector

Return

A jQuery object either containing the elements matched or empty.

.children() Example Traversal  <<  Top

Retrieve the children of each element within the matched set.

In the example below we select all children of 'h3' elements within the .content section of the page and turn the background colour of their children yellow.


$(function(){
  $('#btn1').on('click', function() {
    $('.content h3').children()
                 .css('backgroundColor', 'yellow');
  });
});

Press the button below to action the above code:

.children( selector ) Example Traversal  <<  Top

Retrieve the children of each element within the matched set that match the specified selector.

In the example below we select all 'span' element children of 'h3' elements within the .content section of the page and turn the background colour of their children orange. Notice that with the additional selector filter only the 'span' elements on the right are changed within our 'h3' elements.


$(function(){
  $('#btn2').on('click', function() {
    $('.content h3').children('span')
                 .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code:

Related Tutorials

jQuery Basic Tutorials - Lesson 6 - Tree Traversal