Skip to content

Instantly share code, notes, and snippets.

@jjmu15
Created January 27, 2014 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjmu15/8646069 to your computer and use it in GitHub Desktop.
Save jjmu15/8646069 to your computer and use it in GitHub Desktop.
Remove specified class - vanilla JS
// removeClass, takes two params: element and classname
function removeClass(el, cls) {
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
el.className = el.className.replace(reg, " ").replace(/(^\s*)|(\s*$)/g,"");
}
@kellyjoe256
Copy link

What do you think about this

function removeClass(el, cls) {
    'use strict';
    if ( hasClass(el, cls) ) {
        var newElementClass = ' ' + el.className + ' ';
        var newClassName = ' ' + cls + ' ';

        var re = new RegExp(''+newClassName+'', 'g');
        newClassName = newElementClass.replace(re, '');
        newClassName = newClassName.replace(' ', ''); 
        // or can use String method trim e.g newClassName.trim()

        el.className = newClassName;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment