Created
July 19, 2013 03:22
-
-
Save sivagao/6034873 to your computer and use it in GitHub Desktop.
Manipulating classes with javascript.
http://blog.alexanderdickson.com/manipulating-classes-with-javascript
This file contains hidden or 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
// Back in the old days, classes were manipulated on elements simply with the className property. | |
// This led to an awful lot of string manipulation for manipulating the class attribute. | |
Thankfully, the classList property has popped up recently. | |
var supportsClassList = ({}).toString.call(document.body.classList) == '[object DOMTokenList]'; | |
the fallback implementation | |
var getClasses = function(element){ | |
return element.className.split(/\s+/); | |
} | |
var addClass = function(element, classname){ | |
return element.className += " " + className; | |
} | |
var removeClass = function(element, className){ | |
return element.className = (" " + element.className + " ").replace(" " + className + " ", " "); | |
} | |
var toggleClass = function(element, className){ | |
return ((" " + element.className + " ").indexOf(className) > -1 ? addClass : removeClass)(element, className); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment