0

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

1
  • Where does the variable parent come from? And what does the bracket() function do? Is parent perhaps another global variable that's set by something else? Commented Oct 24, 2009 at 4:59

5 Answers 5

4
  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.
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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!

Comments

0

You should break the recursion like this

if(ele.parentNode) return;

parentNode.name is not supported by firefox

1 Comment

That should be negated (if (!ele...), yes?
0

Maybe try something like this:

var anc = [];

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.