Last active
August 29, 2015 14:07
-
-
Save Fardinak/057f74cc22b15db35044 to your computer and use it in GitHub Desktop.
Element has parent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Addressing the issue provided in the following Stackoverflow question: | |
* Check if class exists somewhere in parent - vanilla JS | |
* http://stackoverflow.com/q/16863917/717221 | |
*/ | |
function hasParent(element, parentSelector) { | |
var potentialParents = document.querySelectorAll(parentSelector); | |
for(i in potentialParents) if(potentialParents[i].contains(element)) | |
return potentialParents[i]; | |
return false; | |
} | |
// USAGE | |
var elm = document.getElementById('the-element'); | |
if(hasParent(elm, '.some.wired > .selector')) alert('Oh, wow, she\'s here!'); | |
/* | |
* Here's another method, provided by `dystroy` | |
* It's restricted to a single class name selector, | |
* yet way faster than any other method. | |
* http://stackoverflow.com/a/16863971/717221 | |
*/ | |
function hasSomeParentTheClass(element, classname) { | |
if (element.className.split(' ').indexOf(classname)>=0) return true; | |
return element.parentNode && hasSomeParentTheClass(element.parentNode, classname); | |
} | |
// USAGE | |
var elm = document.getElementById('the-element'); | |
if(hasParent(elm, 'the-class')) alert('Oh, wow, she\'s here!'); | |
/* | |
* Benchmarked @ http://jsperf.com/element-has-parent | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment