Skip to content
Advertisement

How to check className in a switch statement when an element has multiple classes

In the example below I just want the option clicked to display in an alert. I’m trying to use a switch statement to determine what class was clicked. My example would work if my divs did not each contain more than one class. I tried using classList.contains in my switch statement to no avail. Is there a way I can get this working without changing my use of a switch statement?

function optionClicked(){
  switch( this.className ){
    case 'option1':
      alert( 'user clicked option1' );
      break;
    case 'option2':
      alert( 'user clicked option2' );
      break;
    case 'option3':
      alert( 'user clicked option3' );
      break;      
  }
}

function optionTabs(){
  var optionTabs = document.querySelectorAll( 'div' ),
  i = 0;
  
  for( i; i < optionTabs.length; i++ ){
    optionTabs[ i ].addEventListener( 'click', optionClicked );
  }
}

optionTabs();
html {
  background-color: #eee;
  font-family: sans-serif;
}
div {
  cursor: pointer;
  margin: 1.1rem;
  padding: 1rem;
  background-color: #fff;
  letter-spacing: 0.05rem;
  border-radius: 1rem;
}
div:hover {
  background-color: #555;
  color: #eee;
}
<div class="option1 more">option 1</div>
<div class="option2 classes">option 2</div>
<div class="option3 here">option 3</div>

Advertisement

Answer

The following should work in your switch statement:

function optionClicked(){
  var cls = this.classList;
  switch( true ){
    case cls.contains('option1'):
      alert( 'option1' );
      break;
    case cls.contains('option2'):
      alert( 'option2' );
      break;
    case cls.contains('option3'):
      alert( 'option3' );
      break;      
  }
}

function optionTabs(){
  var optionTabs = document.querySelectorAll( 'div' ),
  i = 0;
  
  for( i; i < optionTabs.length; i++ ){
    optionTabs[ i ].addEventListener( 'click', optionClicked );
  }
}

optionTabs();
html {
  background-color: #eee;
  font-family: sans-serif;
}
div {
  cursor: pointer;
  margin: 1rem;
  padding: 1rem;
  background-color: #fff;
  letter-spacing: 0.05rem;
}
div:hover {
  background-color: #555;
  color: #eee;
}
<div class="option1 more">option 1</div>
<div class="option2 classes">option 2</div>
<div class="option3 here">option 3</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement