Created
September 12, 2016 04:33
-
-
Save liximomo/1b742f5220ea325c9053f6f134a132bb to your computer and use it in GitHub Desktop.
check if an element is a descendant of another
This file contains 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
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