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'))
2

4 Answers 4

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.

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

Comments

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?

1 Comment

Does the downvoter care to drop a comment ?
0

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

Comments

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.

3 Comments

What if you're looking for cat and it has catalog? -1
@PeeHaa埽,@Doorknob fair enough. I didn't think it through :). Nonetheless, you can access the value of the class attribute by part one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.