0

How can I select one particular class in an element with many ones ? Here's my problem :

<div class="oneclass secondclass theclass otherclass"></div>

And in my javascript :

var theclass = this.className; // This part must be changed
var otherclass = this.className; // This one too
if (otherclass == "value" ) {
for (n = 1 ; n < mytab.length ; n ++) { if (mytab[n].name == theclass) { ... } }
}

I have an onclick function that needs to compare the classes myclass and minorclass, the two others aren't important. One more thing, because I need to compare the classes, I don't know the name of minorclass and theclass (and oneclass may not be the same, too)

  • 4
    `if(elm.classList.contains("theclass"))elm.classList.add("differentclass") ` – dandavis May 19 '15 at 07:05
  • possible duplicate of ["hasClass" with javascript? or site with jquery to javascript translation?](http://stackoverflow.com/questions/5085567/hasclass-with-javascript-or-site-with-jquery-to-javascript-translation) – andyb May 19 '15 at 07:08

2 Answers2

1

You can use the classList property for this. It's array-like, but has a method called 'contains' which does exactly what you expect (and what you need).

Chris Browne
  • 1,582
  • 3
  • 15
  • 33
0

var elem = document.querySelector('.theclass');

elem.classList.contains('otherclass') ? elem.classList.remove('otherclass') : elem.classList.add('otherclass');
<div class="oneclass secondclass theclass otherclass"></div>
Roger Causto
  • 153
  • 1
  • 3