.children()S2C 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() ExampleTop

Retrieve the children of each element within the matched set.

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


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

Press the button below to action the above code:


.children( selector ) ExampleTop

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 'h4' elements within the '#main' 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 'h4' elements.


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

Press the button below to action the above code: