skip to Main Content

i’m getting this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')

my code:

for (var i =0;i<7;i++){
    document.querySelectorAll("button")[i].addEventListener("click",handleClick);
}
function handleClick(i) {
    var name=document.querySelectorAll("button")[i].innerHTML;
    alert(name+" got clicked!");
} 

i tried using bind but it was also giving the same error, also tried using anonymous function that also didn’t work.

I am trying to customize the alert with each button name but this all is just not working.

I think it might be because of the loop that this error is coming but i can’t understand why

2

Answers


  1. You forgot to pass the i argument

    for (let i =0;i<7;i++){
        document.querySelectorAll("button")[i].addEventListener("click",() => handleClick(i));
    }
    function handleClick(i) {
        var name=document.querySelectorAll("button")[i].innerHTML;
        alert(name+" got clicked!");
    } 
    
    Login or Signup to reply.
  2. If you are trying to get the alert according to the button name you can simply do this…….

    <button type="button" onclick="getAlert(this)">This is button 1</button>
    <button type="button" onclick="getAlert(this)">This is button 2</button>
    
    function getAlert(e)
    {
        let thisIsButtonName = e.textContent
        console.log(thisIsButtonName)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search