## jQuery parent() Method
The `parent()` method is a built-in jQuery traversal method used to find and return the direct parent element of the selected element(s).
---
### Definition and Usage
The `parent()` method travels a single level up the DOM (Document Object Model) tree to retrieve the immediate parent of each element in the current matched set.
* **DOM Tree Traversal:** This method only travels **one level up** the DOM tree. If you need to traverse multiple levels upward to find grandparents or other ancestors, use the [parents()](./traversing-parents.md) or [parentsUntil()](./traversing-parentsUntil.md) methods instead.
* **Downward Traversal:** If you need to traverse down the DOM tree to find children or descendants, use the [children()](./traversing-children.md) or [find()](./traversing-find.md) methods.
---
### Syntax
```javascript
$(selector).parent(filter)
```
#### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `filter` | String | *Optional.* A selector expression (like a class, ID, or tag name) to narrow down the search. If specified, the method will only return the parent element if it matches this selector. |
---
### Code Examples
#### Example 1: Get the Direct Parent of an Element
The following example finds the direct parent of each `
` element and applies a red border and text color to it.
```html
div (great-grandparent)
ul (grandparent)
- li (direct parent)
span (target element)
```
**Visual DOM Hierarchy Result:**
* `div` (great-grandparent)
* `ul` (grandparent)
* `li` (direct parent) β **[Styled with Red Border & Text]**
* `span` (target element)
---
#### Example 2: Filtering the Parent Search
You can pass an optional selector to filter the parent element. In this example, we target the parent of `` elements, but only apply styles if the parent is an `` element with the class `"highlight"`.
```javascript
$(document).ready(function(){
// Only returns the parent if it is an element with class "highlight"
$("span").parent("li.highlight").css({"background-color": "yellow"});
});
```
---
#### Example 3: Selecting `` Parents of `
` Elements
This example demonstrates how to target and style only the `
` elements that act as immediate parents to `
` elements.
```javascript
$(document).ready(function(){
$("p").parent("div").css({"border": "2px solid blue", "padding": "10px"});
});
```
---
### Key Considerations
1. **Single-Level Limit:** Remember that `parent()` stops exactly one level up. If your target element is wrapped inside another container (e.g., `
`), calling `$("span").parent()` will only return the `` element, not the `
`.
2. **Multiple Elements:** If the jQuery selector matches multiple elements, `.parent()` will return a collection containing the unique parent elements for all matched items.
3. **Empty Results:** If a parent element does not match the provided `filter` selector, the returned jQuery object will be empty (length of 0).