.parents()S2C Home « Traversal « .parents()

Ancestor element retrieval.

Description

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

  • Use the .parent() method instead if you only want to go up one level to retrieve the immediate parent.

Syntax

Signature Description
.parents()Retrieve the ancestors of each element within the matched set.
.parents( selector )Retrieve the ancestors of each element within the matched set that matches 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.

.parents() ExampleTop

Retrieve the ancestors of each element within the matched set.

In the example below we select the ancestors of the '#main form' sections of the page and turn the background colour to olive.


$(function(){
  $('#btn23').on('click', function() {
    $('#main form').parents()
              .css('backgroundColor', 'olive');
  });
});

Press the button below to action the above code:


.parents( selector ) ExampleTop

Retrieve the ancestors of each element within the matched set that matches the specified selector.

In the example below we select only 'p' ancestors of each 'a' element within the #main section of the page and turn the background colour to orange.


$(function(){
  $('#btn24').on('click', function() {
    $('#main a').parents('p')
                .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code: