Skip to content

Instantly share code, notes, and snippets.

@moqmar
Last active February 13, 2017 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moqmar/0995cf6595201f7a062fb173cb4ab938 to your computer and use it in GitHub Desktop.
Save moqmar/0995cf6595201f7a062fb173cb4ab938 to your computer and use it in GitHub Desktop.
// Parent Elements - e.P("body") - https://gist.github.com/moqmar/0995cf6595201f7a062fb173cb4ab938
(function(E){E.matches||(E.matches=E.matchesSelector||E.msMatchesSelector||E.webkitMatchesSelector)})(Element.prototype)
Element.prototype.P = function(s) {
var e = this;
if (!s || typeof s == "number") for (var i = 0; i < (s || 1); i++) e = e ? e.parentElement : e;
else if (typeof s == "string") while (e && !e.matches(s)) e = e.parentElement;
else while (e && e != s) e = e.parentElement;
return e
}
// Parent Elements - e.P("body") - https://gist.github.com/moqmar/0995cf6595201f7a062fb173cb4ab938
(function(E){E.matches||(E.matches=E.matchesSelector||E.msMatchesSelector||E.webkitMatchesSelector)})(Element.prototype)
Element.prototype.P=function(s){var e=this
if(!s||typeof s=="number")for(var i=0;i<(s||1);i++)e=e?e.parentElement:e
else if(typeof s=="string")while(e&&!e.matches(s))e=e.parentElement
else while(e&&e!=s)e=e.parentElement
return e}

parentElement Helper for JavaScript

Easily get to the n-th parent element or to the first parent element which matches a selector:

var element = document.getElementsByClassName("example")
element.P(2) // ➜ element.parentElement.parentElement
element.P()  // ➜ element.parentElement
element.P("body") // ➜ document.body, or null if the element doesn't exist in the DOM
element.P(document.head) // ➜ document.head or null

Compatibility

This script is compatible with all major browsers, including IE9+.


public domain / cc0

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