recursive function always return null

S

samuelberthelot

Hi,

Here's the function:

function getParentElementByTagName(child, TagName){
var cn;
if (child.parentElement){
cn = child.parentElement;
if (child.parentElement.tagName == TagName){
return cn;
}else{
getParentElementByTagName(child.parentElement, TagName);
}
}
}

although it finds the element, the function returns null ( on the line
'return cn', cn is not null though). Is my algorithm wrong ?

thanks
 
M

Martin Honnen

function getParentElementByTagName(child, TagName){
var cn;
if (child.parentElement){

W3C DOM knows a property parentNode but not a property named
parentElement (which is IE DOM). IE 5 and later have parentNode too so
you probably want to use parentNode and not parentElement.
As for the problem, which browser does that occur with?
 
S

samuelberthelot

Hi,
I'm using IE 6 and Firefox. I've replaced parentElement with parentNode
but still returned undefined, although in the function I can see it
finds the right node :(
something must be wrong with the recursion.
 
M

Martin Honnen

I'm using IE 6 and Firefox. I've replaced parentElement with parentNode
but still returned undefined, although in the function I can see it
finds the right node :(
something must be wrong with the recursion.

You need to use return on the recursive call
getParentElementByTagName(child.parentElement, TagName);

return getParentElementByTagName(child.parentNode, TagName);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top