Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to tell if an HTML element has a particular class in JavaScript?

How to tell if an HTML element has a particular class in JavaScript?

Problem

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'))
Problem courtesy of: at.

Solution

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.

Solution courtesy of: Bart

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

How to tell if an HTML element has a particular class in JavaScript?

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×