.parents() JQ 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() Example Traversal  <<  Top

Retrieve the ancestors of each element within the matched set.

In the example below we select the ancestors of the .content section of the page and turn the background colour to olive.


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

Press the button below to action the above code:

.parents( selector ) Example Traversal  <<  Top

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 .content section of the page and turn the background colour to orange.


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

Press the button below to action the above code:

Related Tutorials

jQuery Basic Tutorials - Lesson 6 - Tree Traversal