Native JavaScript hasClass()

πŸ‘‹ Ciprian on Thursday, August 22, 2019 in JavaScript
Last modified on Thursday, August 22, 2019

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy