If you want to switch the class to an element, you can try this suggestion. I tried it in different cases, with or without other classes per element, and I think it works a lot:
(function(objSelector, objClass){ document.querySelectorAll(objSelector).forEach(function(o){ o.addEventListener('click', function(e){ var $this = e.target, klass = $this.className, findClass = new RegExp('\\b\\s*' + objClass + '\\S*\\s?', 'g'); if( !findClass.test( $this.className ) ) if( klass ) $this.className = klass + ' ' + objClass; else $this.setAttribute('class', objClass); else { klass = klass.replace( findClass, '' ); if(klass) $this.className = klass; else $this.removeAttribute('class'); } }); }); })('.yourElemetnSelector', 'yourClass');
Christiyan Jun 26 '17 at 14:30 2017-06-26 14:30
source share