Skip to content

Instantly share code, notes, and snippets.

@liximomo
Created September 12, 2016 04:33
Show Gist options
  • Save liximomo/1b742f5220ea325c9053f6f134a132bb to your computer and use it in GitHub Desktop.
Save liximomo/1b742f5220ea325c9053f6f134a132bb to your computer and use it in GitHub Desktop.
check if an element is a descendant of another
var nodeContainsWorksWithTextNodes = false;
try {
var testParent = document.createElement('div'),
testText = document.createTextNode(' ');
testParent.appendChild(testText);
nodeContainsWorksWithTextNodes = testParent.contains(testText);
} catch (exc) {}
function isDescendant(parent, child, checkEquality) {
if (!parent || !child) {
return false;
}
if (parent === child) {
return !!checkEquality;
}
// If parent is not an element, it can't have any descendants
if (parent.nodeType !== 1) {
return false;
}
if (nodeContainsWorksWithTextNodes || child.nodeType !== 3) {
return parent.contains(child);
}
var node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment