0

I'm trying to have menuSelected.textContent (which is my only h4) changed to the textContent of what of the option that I choose from the menu. I'm getting this error and I'm wondering what I'm doing wrong. Can y'all please help me? Thank you.

I've tried setting menuSelected.textContent = menu[0].textContent before the loop, but then it doesn't change when I click on the others menus (menu[1], menu[2], etc.)

var menu = document.querySelectorAll(".menu a");
var menuSelected = document.querySelector("h4");

//menu controls

for(var i = 0; i < menu.length; i++){
    menu[i].addEventListener("click", function(){
        menuSelected.textContent = menu[i].textContent;
    });
}

The console shows this error:

0: Unable to get property 'textContent' of undefined or null reference

Nico Diz
  • 1,484
  • 1
  • 7
  • 20

1 Answers1

1

I guess the problem is the for loop you're using to generate the click listeners for the menu elements.

for(var i = 0; i < menu.length; i++){
    menu[i].addEventListener("click", function(){
        menuSelected.textContent = menu[i].textContent;
    });

}

i is a local variable which ain't available inside the click events callback function. Well, actually it is but it holds the last value after being incremented in your for-loop which is always the arrays length. So if you try to access menu[i].textContent it tries to access an element out of the bounds of the array.

You need to give the function the special e parameter which holds the event and the object that triggered it:

for(var i = 0; i < menu.length; i++){

    menu[i].addEventListener("click", function(e){
        menuSelected.textContent = e.target.textContent;
    });
}
obscure
  • 11,916
  • 2
  • 17
  • 36
  • Wow, this actually works. I kinda understand why but I'm not 100% sure. I'll definetly look it up exactly what this 'e' paramenter means. Thanks a lot!!!! – Guilherme Cenci Jun 27 '19 at 20:31
  • Glad I could help Guilherme! There's a good explanation hiding here: [https://stackoverflow.com/questions/35936365/what-exactly-is-the-parameter-e-event-and-why-pass-it-to-javascript-functions](https://stackoverflow.com/questions/35936365/what-exactly-is-the-parameter-e-event-and-why-pass-it-to-javascript-functions) – obscure Jun 27 '19 at 20:32