views:

234

answers:

5

I'm writing a js recursion function to find all ancestors of an element a user clicked on. my code is like this:

/**a global variable.*/
var anc; 

function getAncestors(e){  
 var ele = e.target; 
 var parentName = ele.parentNode.name;    
 anc +=bracket(parentName); 

 if (parentName.toLowerCase() == "undefined" ) return;    
 else getAncestors(parent);     
}

I ran it using firefox, but there's an error message in the error console, "Error: ele.parentNode is undefined".

also, when i reset anc = ' '; it didn't work either.

Thanks!

Paul

+2  A: 

You might want to take a look at how they implement the parents function in jQuery.

cdmckay
+2  A: 

An undefined value, per Javascript standards, doesn't have a name attribute -- so rather than trying to get the name in one gulp, just do a var parent = e.target.parentNode; and bail out if THAT is undefined!

Alex Martelli
+4  A: 
  1. parent is undefined. You may have meant ele.parentNode, but see below.
  2. By name convention and by .target, I take it e is an event. But you pass parent, which probably isn't an event.
  3. You probably want to check that ele.parentNode is valid before getting it's properties.
Justin Love
A: 

You should break the recursion like this

if(ele.parentNode) return;

parentNode.name is not supported by firefox

Xinus
That should be negated (`if (!ele...`), yes?
Justin Love
A: 

Maybe try something like this:

var anc = [];

function getAncestors(element) {
  if (element.parentNode) {
    anc.push(element.parentNode);
    getAncestors(element.parentNode);
  }
}
wambotron