Javascript does element have class

If you need to check if an element has a given class, there are a few ways. jQuery has a hasClass function. If you’re limited to users using IE10 or a real browser, then you can use the Element.classList property.

But if you have to cater to old IE users, and aren’t using jQuery, then you can use the following to check to see if an element has a class. Just put this in one of your header script files, before anything that would use it:

if (!Object.prototype.hasClass) {
Object.prototype.hasClass = function (x) {
if (!this.className || !this.className.indexOf) {
return false;
return (" " + this.className + " ").indexOf(" " + x + " ") >= 0;

var elem = document.getElementById("div1");
var hasRed = elem.hasClass("red");

Leave a Reply

Your email address will not be published.