Some CSS-related javascript utility functions
Par J.Ducastel le vendredi 16 septembre 2005, 20:04 - Formules - Lien permanent
Hi folks. Nothing very bright or revolutionary, but here is a tiny library to play with CSS and javascript. More elaborate tricks to come. Hope it helps.
- bool hasClass(DOM obj, string cName)
- bool hasClasses(DOM obj, array classes)
- bool addClass(DOM obj, string cName)
- bool removeClass(DOM obj, string cName)
- bool swapClasses(DOM obj, string class1, string class2)
- bool switchClass(DOM obj, string to, string from)
- array getElementsByClassName(string className, [DOM container],[string tag])
/* CSS-related javascript functions by Fred Bird http://fredbird.org
License : Public Domain file version 16/09/2005 09:30:45 */ /* has the DOM
object a certain class ? obj = DOM object, cName = a class name */ function
hasClass(obj,cName) { return new RegExp('\\b'+cName+'\\b').test(obj.className);
} /* has the DOM object a set of classes ? obj = DOM object, classes=array of
class names */ function hasClasses(obj,classes) { for (f=0;
f<classes.length; f++) { if (!hasClass(obj,classes[i])) return false; }
return true; } /* add a class to a DOM object if necessary obj = DOM object,
cName = a class name */ function addClass(obj,cName) { if
(!hasClass(obj,cName)) { obj.className+=obj.className?' '+cName:cName; } return
true; } /* removes a class from a DOM object obj = DOM object, cName = a class
name */ function removeClass(obj,cName) { if (!hasClass(obj,cName)) return
false; var rep=obj.className.match(' '+cName)?' '+cName:cName;
obj.className=obj.className.replace(rep,''); return true; } /* swap two classes
for a DOM object, whatever provided order */ function
swapClasses(obj,class1,class2) { if (hasClass(obj,class1)) {
removeClass(obj,class1); addClass(obj,class2); return true; } if
(hasClass(obj,class2)) { removeClass(obj,class2); addClass(obj,class1); return
true; } return false; } /* sets class 'to' to the DOM object obj, removes class
'from' if necessary */ function switchClass(obj,to,from) { if
(hasClass(obj,from)) removeClass(obj,from); addClass(obj,to); return true; } /*
returns an array of DOM objects having the provided class name within object
'container' and with tag name 'tag' some code from
http://www.webmasterworld.com/forum91/1757.htm (unbugged) */ function
getElementsByClassName(className,container,tag) { // default container to
document container=container||document; // default tag to * tag=tag||'*'; //
listing container descendants var all =
container.all||container.getElementsByTagName(tag); var found=new Array(); //
searching for targets for (f=0; f<all.length; f++) { var el=all[f]; if
(hasClass(all[f],className)) { found.push(all[f]); } } return found; }