0

Why function(){ return element.innerHTML } returns undefined ?

var demo = document.getElementById('demo');
demo.innerHTML = endangeredSpecies("Europe", "Cave bear");

function endangeredSpecies(continent, species) {
    var contin = document.querySelectorAll('[data-continent]');
  contin.forEach(function(div){
    if(div.getAttribute('data-continent') == continent){
                var children = [].slice.call(div.children);
        children.forEach(function(child) {
                    if(child.getAttribute('data-species') == species) {
                return child.innerText;
                }
            })
     }
  })
}

Fiddle

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
RegarBoy
  • 3,228
  • 1
  • 23
  • 44
  • It doesn't, but you're not returning from the function you think you are. – adeneo May 17 '17 at 17:31
  • You are not returning anything https://jsfiddle.net/jondion/0ad7akkb/ – Jonathan Dion May 17 '17 at 17:32
  • A link to JSFiddle is fine, but you must include the full code in the question itself, too. Use the code snippet feature to make it runnable inside the question. – JJJ May 17 '17 at 17:32
  • Duplicate of http://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function – JJJ May 17 '17 at 17:34

1 Answers1

2

You function doesn't return anything, also return inside forEach doesn't return the value. Assign it to a variable and return it from function liek

var demo = document.getElementById('demo');
demo.innerHTML = endangeredSpecies("Europe", "Cave bear");

function endangeredSpecies(continent, species) {
    var contin = document.querySelectorAll('[data-continent]');
  var val;
  contin.forEach(function(div){
    if(div.getAttribute('data-continent') == continent){
                var children = [].slice.call(div.children);
        children.forEach(function(child) {
                    if(child.getAttribute('data-species') == species) {
                val =  child.innerText;
                }
            })
     }
  })
  return val;
}

JSFIDDLE

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400