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

4
  • It doesn't, but you're not returning from the function you think you are. Commented May 17, 2017 at 17:31
  • You are not returning anything jsfiddle.net/jondion/0ad7akkb Commented May 17, 2017 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. Commented May 17, 2017 at 17:32
  • Duplicate of stackoverflow.com/questions/34653612/… Commented May 17, 2017 at 17:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.