Native JavaScript hasClass()

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

These JavaScript snippets implement a native hasClass() function (inspired by jQuery and dubbed elementHasClass()), which checks if an element has a certain class.

// Method #1: Use JavaScript element.className
function elementHasClass(element, className) {
    return (element.className === className);
}

// Method #2: Use JavaScript element attribute getter
function elementHasClass(element, className) {
    return (indexOf(element.getAttribute(className)));
}

// Method #3: Use JavaScript element.className (RegEx)
function elementHasClass(element, className) {
    return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className);
}

// Usage
if (elementHasClass(document.querySelector('.element'), 'active')) {
    // Do this or do that
}

A prototype approach to the above solution is:

// Method #4: Prototype
Element.prototype.elementHasClass = function(className) {
    return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};

// Usage
if (document.querySelector('.element').elementHasClass('active')) {
    // Do this or do that
}

Personally, I would steer away from the RegEx ones, namely methods 3 and 4.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

👋 Added by Ciprian on Thursday, August 22, 2019 in JavaScript. Last modified on Thursday, August 22, 2019.

Contribute!

Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy