JS - Recursion (basic)
by Zacc206
HTML
<!-- Place a needle in a haystack-->
<div id="haystack">
<div>
<div>
<div>
<div>
<div id="needle"></div>
</div>
</div>
</div>
</div>
</div>
JavaScript
console.clear();
var haystack = document.getElementById('haystack');
console.log(FindNeedle(haystack));
function FindNeedle(elem) {
if (elem.id === "needle") {
return "Needle found!";
} else if (getFirstChild(elem) === null) {
return "Just hay."
} else {
return FindNeedle(getFirstChild(elem));
}
}
function getFirstChild(elem){
var child = elem.children[0]
if(child){
return child;
} else {
return null;
}
}