...

View Full Version : Count Parent Elements



ubh
12-21-2008, 12:16 PM
Hi I am using a event listener for clicked elements. The event listener limits a bubble up of elements to point to this specifically clicked element before preforming the rest of my function.

Great it all works fine, but now that I am pointing to my element how would one go about counting the number of specific parent elements this clicked element has?

vwphillips
12-21-2008, 08:45 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/

function Test(obj){
var cnt=0;
while(obj.parentNode&&obj.nodeName!='BODY'){
cnt++;
obj=obj.parentNode;
}
alert(cnt);
}
/*]]>*/
</script></head>

<body>
<div >
<div >
<a onclick="Test(this);">Click Me</a>
</div>
</div>

</body>

</html>

ubh
12-21-2008, 08:51 PM
Hey vwphillips,
as always great code!! This gets me back on track, thanks m8!

<--Runs to add this to his JS lib :)

jkd
12-21-2008, 09:22 PM
I don't see the need for a string comparison... document.parentNode === null, so:



function countAncestors(node) {
if (node.parentNode === null)
return 0;
else
return 1 + countAncestors(node.parentNode);
}


Or if you hate recursion:


function countAncestors(node) {
for (var count = 0; node.parentNode !== null; node = node.parentNode)
++ count;
return count;
}

ez4ne12c
12-23-2008, 11:38 PM
Could something like this be used to identify child nodes such as window objects?
ez



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum