.parent()
JQ Home <<
Traversal <<
.parent()
Parent element retrieval.
Description
The .parent()
method is used to retrieve the parent of each element within the matched set.
- The
.parent()
method will only travel a single level up the DOM tree, use the.parents()
method to travel up to grandparents and beyond.
Syntax
Signature | Description |
---|---|
.parent() | Retrieve the parent of each element within the matched set. |
.parent(selector) | Retrieve the parent of each element within the matched set that matches the specified selector. |
Parameters
Parameter | Description | Type |
---|---|---|
selector | A string containing a CSS or custom jQuery selector to match elements against. | Selector |
Return
A jQuery
object either containing the elements matched or empty.
.parent()
Example
Traversal << Top
Retrieve the parent of each element within the matched set.
In the example below we select the parent of each 'a' element within the .content section of the page and turn the background colour to yellow.
$(function(){
$('#btn21').on('click', function() {
$('.content a').parent()
.css('backgroundColor', 'yellow');
});
});
.parent( selector )
Example
Traversal << Top
Retrieve the parent of each element within the matched set that matches the specified selector.
In the example below we select only 'span' parents of each 'a' element within the .content section of the page and turn the background colour to orange. Notice that with the additional selector filter only the 'span' elements on the right are changed.
$(function(){
$('#btn22').on('click', function() {
$('.content a').parent('span')
.css('backgroundColor', 'orange');
});
});
Related Tutorials
jQuery Basic Tutorials - Lesson 6 - Tree Traversal