(This post has been edited since its original proposal to remove ancestorQuerySelector
, which was essentially the same as Element.parentElement.closest
, and rename ancestorQuerySelectorAll
to simply ancestors
.)
Pretty self-explanatory: where Element.querySelector
returns the first matching child element, Element.querySelectorAll
returns all matching child elements, and Element.closest
returns the first ancestor matching a given selector query, Element.ancestors
would return a NodeList
(like querySelectorAll
) of all ancestors matching a given selector query (similar to jQuery’s parents()
function).
Implementation / prollyfill:
Element.ancestors = function ancestors(selector) {
// this would use a (non-live) NodeList, but there doesn't appear to be an API for that
var matchingAncestors = [];
var parent = this.parentElement;
while (parent) {
if (parent.matches(selector)) matchingAncestors.push(parent);
parent = parent.parentElement;
}
return parent;
}