Skip to content

Instantly share code, notes, and snippets.

@jordandobson
Created June 8, 2011 00:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordandobson/1013528 to your computer and use it in GitHub Desktop.
Save jordandobson/1013528 to your computer and use it in GitHub Desktop.
Mobile JavaScript Library for HTML Class Attribute Manipulation
(function(document){
window.CLS = window.CLS || {};
CLS.add = function(el, cn){
if(!CLS.exists(el, cn)){
el.className = el.className ? el.className + ' ' + cn : cn;
}
}
CLS.del = function(el, cn){
if(CLS.exists(el, cn)){
var reg = new RegExp('(\\s|^)'+cn+'(\\s|$)');
el.className = el.className.replace(reg, ' ').replace(/^\s|\s$/,'');
}
}
CLS.set = function(el, cn){
CLS.clear(el);
CLS.add(el, cn);
}
CLS.swap = function(el, cnOld, cnNew, force){
if(CLS.exists(el, cnOld)){
el.className = el.className.replace(cnOld, cnNew);
}else if(force){
CLS.add(el, cnNew);
}
}
CLS.clear = function(el){
if(el.className) el.className = '';
}
CLS.exists = function(el, cn){
return new RegExp('(^|\\s)' + cn + '(\\s|$)').test(el.className);
}
})(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment