A small snippet to determine if a node is child of any one of a selection of nodes.
isChildOf(node, selection) // -> true/false
function( | |
t, // target | |
s, // selected nodes | |
p, // placeholder for target/parents | |
i, // counter | |
o // placeholder for "ownerDocument" | |
){ | |
// iterate over selection | |
for (i = 0; i < s.length; i++) | |
for( | |
// check if the selected node is in the same DOM as the target, | |
// otherwise set p to false to stop this loop from iterating the parentNodes | |
p = t[o='ownerDocument'] === s[i][o] && t; | |
p; // continue iteration as long as parentNodes are present | |
p = p.parentNode) | |
// found a match? return true | |
if (p === s[i]) | |
return!0; | |
// nothing found? return false | |
return!1 | |
} |
function(t,s,p,i,o){for(i=0;i<s.length;i++)for(p=t[o='ownerDocument']===s[i][o]&&t;p;p=p.parentNode)if(p===s[i])return!0;return!1} |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2011 Alex Lohr (formerly Kloss) [email protected] | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
{ | |
"name": "isChildOf", | |
"description": "Check if node is child of a selection of nodes", | |
"keywords": [ | |
"node", | |
"child", | |
"selection", | |
"DOM" | |
] | |
} |
<!DOCTYPE html> | |
<title>Foo</title> | |
<div>Expected value: <b>true</b></div> | |
<div>Actual value: <b id="ret"></b></div> | |
<script> | |
// write a small example that shows off the API for your example | |
// and tests it in one fell swoop. | |
var myFunction = function(t,s,p,i,o){for(i=0;i<s.length;i++)for(p=t[o='ownerDocument']===s[i][o]&&t;p;p=p.parentNode)if(p===s[i])return!0;return!1} | |
document.getElementById( "ret" ).innerHTML = myFunction(document.getElementById( "ret" ), document.getElementsByTagName('div')); | |
</script> |