Skip to content

Instantly share code, notes, and snippets.

@ziggi
Last active August 11, 2022 16:10
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ziggi/2f15832b57398649ee9b to your computer and use it in GitHub Desktop.
Save ziggi/2f15832b57398649ee9b to your computer and use it in GitHub Desktop.
Vanilla JS jQuery.parents() realisation (npm module: https://github.com/ziggi/dom-parents)
Element.prototype.parents = function(selector) {
var elements = [];
var elem = this;
var ishaveselector = selector !== undefined;
while ((elem = elem.parentElement) !== null) {
if (elem.nodeType !== Node.ELEMENT_NODE) {
continue;
}
if (!ishaveselector || elem.matches(selector)) {
elements.push(elem);
}
}
return elements;
};
@LuisSevillano
Copy link

Superb!!! Thanks @ziggi

@ziggi
Copy link
Author

ziggi commented May 22, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment