Reputation: 1594
I've got this really annoying issue where a function returning a value of undefined every time even though the console.log() always shows that there is a value when getting into the first if statement
This is my function
function getElementIdentifier(elem, domSelector) {
if(elem.getAttribute('id') !== null) {
console.log('here');
return elem.id + ' ' + domSelector;
} else {
getElementIdentifier(elem.parentNode, elem.tagName + ' ' + domSelector);
}
}
This is how I call it
getElementIdentifier(elem, '');
Heres a fiddle to replicate it. http://jsfiddle.net/wqCSn/5/ (thanks @adeneo)
Upvotes: 1
Views: 715
Reputation: 7169
Your function does not return value if call self recursively. You should to add return statement ro alternative branch of algorithm
function getElementIdentifier(elem, domSelector) {
if(elem.getAttribute('id') !== null) {
return elem.id + ' ' + domSelector;
} else {
return getElementIdentifier(elem.parentNode, elem.tagName + ' ' + domSelector);
}
}
Upvotes: 3
Reputation: 1027
hmmmm... try this:
function getElementIdentifier(elem, domSelector) {
if(elem.getAttribute('id') !== null) {
console.log('here');
return elem.id + ' ' + domSelector;
} else {
//return the recursion returned value (sounds like inception) but
//you are expecting a value from this function...
return getElementIdentifier(elem.parentNode, elem.tagName + ' ' + domSelector);
}
}
Upvotes: 1