1

I am making a simple calculator. All buttons have .button class attached. However, I also want the numbers to have a .number class attached and operators to have an .operator class.

Using JS to select the element, I can use this but it only works if the element has one class name (.button):

        document.body.addEventListener('click', function (e) {

        if (e.target.className === 'button') {
            document.getElementById('display').innerHTML = e.target.innerHTML;
            e.target.style.opacity = '0.9';
            setTimeout(function() {
                e.target.style.opacity = '1';
            }, 150);
        }
    });

If I add the .number class to the html elements, this stops working. I need to be able to choose all buttons using .button class OR only buttons with .number class, etc.

Is there a way to do this so that I can select elements that have more than one class name using only one class name?

No jQuery, please.

6
  • Can you create codepen or js fiddle for debugging issue easily? Commented Jun 12, 2016 at 17:09
  • 1
    You're doing with your clicked button opacity things you've could easily done using :active in CSS Commented Jun 12, 2016 at 17:12
  • 1
    have you tried using classList.contains("button") instead of className === "button" Commented Jun 12, 2016 at 17:15
  • Man, the word "duplicate" has a pretty loose definition around here, doesn't it? LOL. Even if I had found that other one first, I never would have known it had the answer since I don't use jQuery. Commented Jun 12, 2016 at 17:35
  • @IvánNokonoko Thanks for giving me the code right here. Commented Jun 12, 2016 at 17:46

1 Answer 1

2

use classList's contains() method to test for existence a class on a element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Sign up to request clarification or add additional context in comments.

1 Comment

This did the trick. Thanks. (Although giving an example here of how to change my code like Ivan did would have been more convenient.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.