Last active
December 14, 2015 16:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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