Maciej Mazurek
Maciej Mazurek

Reputation: 41

Adding Click event on all elements with the same class without loop and jQuery

I have to write a code that run click event on all inputs with the same class without a loop and jquery.

What I come up with is :

document.body.addEventListener('click', function (click) {
    if (click.target.className == 'abc') {
        document.frame.screen.value += this.value;
    }
});

and click works but I got undefined instead of value that clicked input contain.

Upvotes: 0

Views: 673

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

and click works but I got undefined instead of value that clicked input contain.

Because you've used this instead of click.target when getting the value; you wanted to use click.target:

document.frame.screen.value += click.target.value;
// Here -----------------------^^^^^^^^^^^^

this in your handler will be document.body. You've correctly used click.target when checking the class, but not when getting the value.

Some notes:

  • FWIW, the usual name for the event parameter in an event handler is event or e, not click.
  • Elements can have multiple classes, which will all be in className. If that's a possible issue for you, you might look at .classList.contains("abc") instead. (classList is available on all modern browsers, and you can polyfill it on obsolete ones.)
  • It's not an issue for input elements, but in future if you want to do this with elements that can have descendant elements, you might need to have a loop to handle the possibility the click was on a descendant of your target element:

    var node = event.target;
    while (!node.classList.contains("abc")) {
        if (node === this) {
            return; // The click didn't pass through a matching element
        }
        node = node.parentNode;
    }
    // Use it here
    

Upvotes: 1

Related Questions