Skip to content

Instantly share code, notes, and snippets.

@raybellis
Last active December 14, 2015 16:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save raybellis/5115997 to your computer and use it in GitHub Desktop.
Save raybellis/5115997 to your computer and use it in GitHub Desktop.
A shim for jQuery that uses the native "classList" property of an element for class modifications, if available.
/*global jQuery */
;(function($) {
/*global document */
"use strict";
if (typeof document !== 'undefined' && ('classList' in document.createElement('a'))) {
var $ = jQuery;
var _addClass = $.fn.addClass;
var _removeClass = $.fn.removeClass;
$.fn.hasClass = function(selector) {
var elem, i, l;
for (i = 0, l = this.length ; i < l; ++i) {
elem = this[i];
if (elem.nodeType === 1 && elem.classList.contains(selector)) {
return true;
}
}
return false;
};
$.fn.addClass = function(value) {
var elem, i, l;
if (typeof value === 'string' && value && value.indexOf(' ') < 0) {
for (i = 0, l = this.length ; i < l; ++i) {
elem = this[i];
if (elem.nodeType === 1) {
elem.classList.add(value);
}
}
} else {
_addClass.apply(this, arguments);
}
return this;
};
$.fn.removeClass = function(value) {
var elem, i, l;
if (typeof value === 'string' && value && value.indexOf(' ') < 0) {
for (i = 0, l = this.length ; i < l; ++i) {
elem = this[i];
if (elem.nodeType === 1) {
elem.classList.remove(value);
}
}
} else {
_removeClass.apply(this, arguments);
}
return this;
};
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment