JavaScript + recursive function returning undefined

I have a simple html structure that I need to go through. For some reason, my recursive function returns "undefined" to any nested nodes, but not to the parent nodes. Unfortunately, this must be native js, without jQuery for this. Thank!

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);
    }
}
+3
source share
3 answers

You just call returnfor a recursive call. In addition, you should check if its result is defined. If so, you can return it or continue the cycle 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;
        };
    }
}​
+13
source

else return hasId(child, id), , .

return , .

+6

You can fix it as follows:

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

console.log(h + " : " + r + " : " + l);

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

All Articles