Created
February 6, 2014 08:17
-
-
Save snowman-repos/8840169 to your computer and use it in GitHub Desktop.
Adding and Removing Classes, without jQuery
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
# Select an element | |
element = document.querySelector(".some-class") | |
# Give class "foo" to the element | |
element.className = "foo" | |
# Adding a class without replacing the current classes | |
element.className += " foo" | |
# removeClass, takes two params: element and classname | |
removeClass = (el, cls) -> | |
reg = new RegExp("(\\s|^)" + cls + "(\\s|$)") | |
el.className = el.className.replace(reg, " ").replace(/(^\s*)|(\s*$)/g, "") | |
removeClass element, "foo" | |
# hasClass, takes two params: element and classname | |
hasClass = (el, cls) -> | |
el.className and new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className) | |
# Check if an element has class"foo" | |
# Show an alert message if it does | |
alert "Element has the class!" if hasClass(element, "foo") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment