Skip to content

Instantly share code, notes, and snippets.

@snowman-repos
Created February 6, 2014 08:17
Show Gist options
  • Save snowman-repos/8840169 to your computer and use it in GitHub Desktop.
Save snowman-repos/8840169 to your computer and use it in GitHub Desktop.
Adding and Removing Classes, without jQuery
# 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