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.

AlwaysLearning
  • 311
  • 4
  • 12

1 Answers1

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

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
  • This did the trick. Thanks. (Although giving an example here of how to change my code like Ivan did would have been more convenient.) – AlwaysLearning Jun 12 '16 at 17:39