getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

Native JavaScript hasClass()

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

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

Related Articles

My Battle Tested Recommendations
Disclaimer: These recommendations contain affiliate links.

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush
SEMrush

Privacy Policy