**Note:** To filter and return multiple specific ancestors, you can separate multiple expressions with commas (e.g., `"div, ul"`). | --- ## Code Examples ### Example 1: Return All Ancestors of an Element The following example selects all ancestor elements of a `` element and applies a red border and text color to them. ```javascript $(document).ready(function(){ $("span").parents().css({ "color": "red", "border": "2px solid red" }); }); ``` **DOM Structure Visualized:** ```text html βββ body (great-great-grandparent) - Styled Red βββ div (great-grandparent) - Styled Red βββ ul (grandparent) - Styled Red βββ li (direct parent) - Styled Red βββ span (selected element) ``` --- ### Example 2: Narrowing the Search with a Filter If you only want to target a specific ancestor, you can pass a selector as a filter. The following example returns only the `
- ` ancestors of the `` element:
```javascript
$(document).ready(function(){
$("span").parents("ul").css({
"color": "red",
"border": "2px solid red"
});
});
```
---
### Example 3: Returning Multiple Specific Ancestors
You can pass multiple comma-separated selectors to the filter parameter. The following example returns both `
- ` and `` ancestors of the `` element: ```javascript $(document).ready(function(){ $("span").parents("li, div").css({ "color": "red", "border": "2px solid red" }); }); ``` --- ## Considerations & Best Practices 1. **Performance Impact:** Because `parents()` traverses all the way up to the `` element, calling it without a filter on a deeply nested DOM tree can impact performance. If you only need the immediate parent, use `.parent()`. If you only need the single nearest matching ancestor, use `.closest()`. 2. **Empty Results:** If no ancestors match the optional filter criteria, the method returns an empty jQuery object (length of 0), and no error is thrown. 3. **Method Chaining:** Like most jQuery traversal methods, `parents()` returns a jQuery object, allowing you to chain other jQuery methods directly after it (e.g., `$("span").parents(".container").addClass("active").show();`).
YouTip