1

Is there an easy way to tell if an HTML element has a specific class? For example:

var element = document.getElementById('something');
if (element.class == 'car')

Of course an element can have multiple classes, so maybe the if statement would have to be of the following form?

if (element.class.includes('car'))
at.
  • 50,922
  • 104
  • 292
  • 461

4 Answers4

2
var element = document.getElementById("myid");
if (element.classList.contains("myclass")) { /* do stuff */ }

Read more on element#classList here: https://developer.mozilla.org/en-US/docs/DOM/element.classList

This link also contains a polyfill for older browsers.

Bart
  • 26,399
  • 1
  • 23
  • 24
0

If using jQuery is an option you can use hasClass() see http://api.jquery.com/hasClass/

If not you can take a look at pure JS implementation - Test if an element contains a class?

Community
  • 1
  • 1
kgr
  • 9,750
  • 2
  • 38
  • 43
0

For strange reasons the name of the member containing the class(es) is className, not class. Multiple class names are separated by space.

6502
  • 112,025
  • 15
  • 165
  • 265
0

You need to use:

 class = document.getElementById("{id_of_element").getAttribute("class");

then

 String[] vals = class.split(" ");
 var match = false;
 for (i = 0; i < vals.length;i++) {
   if (vals[i].equalsIgnoreCase('car') {
     match = true;
     break;
   }
 }

 if (match) {
  //do something
 }

HTH.

John Brown
  • 189
  • 1
  • 7