Why isn't delegation working?

  • 0
    I am learning about delegation in JS. I found an article where everything is described in detail, and there is an example code. Everything works fine in the example: https://codesandbox.io/ s / event-delegation-example -...

    I copied the example and adapted it for my task. When hovering over className, it swears at "non-computed variable".

    let calc = document.querySelector (". calc");

    calc.addEventListener ('click', function (event) {
    if (event.target.className === 'button') {
    console.log ('Click!');
    }
    });



    Why doesn't it work for me?
    JavaScript Grace Jacobs, Apr 3, 2019

  • 1 Answers
  • 0
    the condition className === 'button' won't work because it's not 'button' , but 'button num3' or something like that. < br />


    Check with classList .contains () or better yet event.target.closest ('button') - this will work even if there are icons inside the button, for example, and the click hits them.



    const calc = document.querySelector('.calc');
    calc.addEventListener('click', calcClickHandler);

    function calcClickHandler(event) {
    const button = event.target.closest('button');
    if (button) {
    console.log('Click!', button);
    }
    });




    And instead of classes with actions like minus, plus, I would recommend using date attributes.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!