JavaScript + recursive function returning undefined

javascript, recursion

Solution

You are simply the call to `return` on the recursive call. Also, you should test whether its result is defined. If yes, you can return it, or continue looping if not.

var h = hasId(container, 'head');
var l = hasId(container, 'left');
var r = hasId(container, 'right');

console.log(h + " : " + r + " : " + l);
//[object HTMLDivElement] : undefined : undefined

function hasId(ele, id) {
    for (var i = 0; i < ele.childNodes.length; i++) {
        var child = ele.childNodes[i];
        if(child.id == id) return child;
        else {
          var next = hasId(child, id);
          if(next) return next;
        };
    }
}​

Problem

I have a simple html structure that I need to traverse. For some reason my recursive function returns 'undefined' on any nested nodes, but not for parent nodes. Unfortunately this needs to be native js, no jQuery for this one. Thanks! HTML: ``` <div id="container"> <div id="head"> <span id="left"><</span> <span id="right">></span> </div> </div> ``` Script: ``` var h = hasId(container, 'head'); var l = hasId(container, 'left'); var r = hasId(container, 'right'); console.log(h + " : " + r + " : " + l); //[object HTMLDivElement] : undefined : undefined function hasId(ele, id) { for (var i = 0; i < ele.childNodes.length; i++) { var child = ele.childNodes[i]; if(child.id == id) return child; else hasId(child, id); } } ```

Original source