0

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.

1
  • this is going to be document.body so value won't exist. Commented Aug 29, 2017 at 10:30

1 Answer 1

1

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
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's a lot! I'm a toddler with javascript and don't fully understand DOM :)

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.