Created
February 23, 2015 20:01
-
-
Save matesnippets/c6c3e1eb7ae881a9547d to your computer and use it in GitHub Desktop.
JavaScript, Add, remove, and toggle a class name in a given DOM element with pure 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
| define(function() { | |
| return { | |
| /** | |
| * Adds a class name to an element | |
| * @param {element} el The target element | |
| * @param {string} clazz The class names wanted to add | |
| */ | |
| add: function addClass(el, clazz) { | |
| var cn = el.className; | |
| // Test for existance | |
| if (cn.indexOf(clazz) != -1) { | |
| return; | |
| } | |
| // Add a space if the element already has class | |
| if (cn != '') { | |
| clazz = ' ' + clazz; | |
| } | |
| el.className = cn + clazz; | |
| }, | |
| /** | |
| * Remove class from a given element | |
| * @param {element} el The targetend element | |
| * @param {class} clazz The class name to remove | |
| */ | |
| remove: function(el, clazz) { | |
| el.className = el.className.replace(new RegExp('(?:^|\\s)' + clazz + '(?!\\S)'), ''); | |
| }, | |
| /** | |
| * Toggles class in element | |
| * @param {element} el Reference to an element | |
| * @param {string} clazz The class name to toggle | |
| */ | |
| toggle: function(el, clazz) { | |
| var cn = el.className; | |
| if (cn.indexOf(clazz) != -1) { | |
| this.remove(el, clazz); | |
| } else { | |
| this.add(el, clazz); | |
| } | |
| } | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment