Created
June 19, 2012 20:05
-
-
Save jonathantneal/2956234 to your computer and use it in GitHub Desktop.
classList polyfill // returns a token list of the class names attached to the element.
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
// classList | @jon_neal | MIT/GPL2 | |
this.Element && !document.lastChild.classList && (function () { | |
Object.defineProperty(Element.prototype, "classList", { | |
configurable: true, | |
get: function () { | |
var | |
join = [].join, | |
push = [].push, | |
splice = [].splice, | |
node = this, | |
list = new function DOMTokenList() { | |
var list = this, index; | |
list.contains = function (value) { | |
var length = list.length; | |
index = -1; | |
splice.apply(list, [0, length].concat((node.getAttribute("class") || "").split(/\s+/))); | |
while (++index < length) if (list[index] == value) break; | |
return index < length; | |
}; | |
list.add = function (value) { | |
if (!list.contains(value)) push.call(list, String(value)); | |
node.setAttribute("class", join.call(list, " ")); | |
}; | |
list.remove = function (value) { | |
if (list.contains(value)) splice.call(list, index, 1); | |
node.setAttribute("class", join.call(list, " ")); | |
}; | |
list.toggle = function (value) { | |
list.contains(value) ? splice.apply(list, [index, 1]) : push.call(list, String(value)); | |
node.setAttribute("class", join.call(list, " ")); | |
}; | |
list.contains(""); | |
}; | |
return Object.defineProperties(node, { | |
className: { | |
configurable: true, | |
get: function () { | |
return join.call(list, " "); | |
}, | |
set: function (value) { | |
this.setAttribute("class", value); | |
list.contains(""); | |
} | |
}, | |
classList: { | |
configurable: true, | |
get: function () { | |
return list; | |
} | |
} | |
}).classList; | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment