Skip to content

Instantly share code, notes, and snippets.

@katspaugh
Created September 29, 2011 12:46
Show Gist options
  • Save katspaugh/1250661 to your computer and use it in GitHub Desktop.
Save katspaugh/1250661 to your computer and use it in GitHub Desktop.
classList shim
var getClassList = (function () {
'use strict';
var ClassList = {}, s = ' ';
ClassList.add = function (cl) {
var className = this.element.className,
list = className.split(s);
list.push(cl);
this.element.className = list.join(s);
};
ClassList.remove = function (cl) {
var className = this.element.className,
list = className.split(s);
for (var i = list.length - 1; i >= 0; i--) {
if (list[i] === cl) {
list.splice(i, 1);
}
}
var newClassName = list.join(s);
if (newClassName !== className) {
this.element.className = newClassName;
}
};
ClassList.contains = function (cl) {
var className = this.element.className;
return !!className && (s + className + s).indexOf(s + cl + s) >= 0;
};
return function (el) {
if (el.classList) {
return el.classList;
} else {
ClassList.element = el;
return ClassList;
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment