Last active
January 19, 2017 14:13
-
-
Save thednp/b157978a2a88286ab1f8d2bd8d6d4031 to your computer and use it in GitHub Desktop.
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
// Element.prototype.classList polyfill | |
// developed by thednp | |
// license MIT | |
if( !('classList' in Element.prototype) ) { | |
(function(){ | |
var className = 'className', add = 'add', classList = 'classList', remove = 'remove', contains = 'contains', | |
prototype = 'prototype', element = 'element'; | |
// classList definition | |
function ClassLIST(elem){ | |
this[element] = elem; | |
this[classList] = elem[classList] = []; | |
var classesLIST = elem[className].replace(/^\s+|\s+$/g,'').split(/\s+/); | |
for (var i = 0; i < classesLIST.length; i++) { | |
this[classList].push(classesLIST[i]); | |
} | |
} | |
// methods | |
ClassLIST[prototype][add] = function(classNAME){ | |
if (this[classList].indexOf(classNAME)<0) { | |
this[classList].push(classNAME); | |
this[element][className] = this[classList].join(' '); | |
} | |
}; | |
ClassLIST[prototype][remove] = function(classNAME){ | |
var classINDEX = this[classList].indexOf(classNAME); | |
if (classINDEX>-1) { | |
this[classList].splice(classINDEX,1); | |
this[element][className] = this[classList].join(' '); | |
} | |
}; | |
ClassLIST[prototype][contains] = function(classNAME){ | |
return this[classList].indexOf(classNAME) > -1; | |
}; | |
Object.defineProperty(Element[prototype], classList, { get: function () { return new ClassLIST(this); } }); | |
}()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment