more class functions…
Update: changed from Object.prototype.hasClass(className) to simply hasClass(element, className) for cross-browser compatibility
Ok… nothing to revolutionary here. This has been done before lots of times. I’ve written two new functions to go along with my hasClass() javascript function.
First is addClass(), which simply adds a class to an object, while preserving the existing classes. Here it is:
function addClass( /*HTMLElement:*/node, /*String:*/className ) {
if( !hasClass(node, className) ) {
node.className = node.className + (node.className ? " " : "") + className;
return true;
}
return false;
};
Use it like this:
addClass(myNode, "myclass");
Next is the removeClass function, which removes a css class from an object. Here it is:
function removeClass( /*HTMLElement:*/node, /*String:*/className ) {
if( hasClass(node, className ) {
node.className = (' '+node.className+' ').replace(' '+className+' ',' ').replace(/^ | $/,'');
return true;
}
return false;
}
And here’s how you use removeClass():
removeClass(myNode, "myclass");
Like I said, nothing revolutionary, but here they are.
my version of the popular addEvent() »
Comments
Comment from spudly
Time: December 17, 2007, 9:57 pm
That looks great. I’ll definitely be using your version instead. I’ll go for less code anyday. Unfortunately, however, I recently discovered that object prototyping doesn’t work on HTMLElements in IE, Safari, or Konqueror. This is apparently because they don’t let you access the constructors for HTMLElement objects. There are some workarounds out there that I have seen, but they don’t look very good to me. I have yet to find a solution (only been looking for a few days) but for the time being I am thinking I might have to change my functions. If I have to, I’ll pass the node in as an argument (for example: hasClass(node, className) instead of element.hasClass(className) ). It’s not as pretty but it’s cross-browser compatible. Check back soon to find out what I decide on ( as well as some functions I am currently working on).
Comment from Jordan
Time: January 19, 2008, 7:49 pm
Nice work! I was just about to write these functions myself, until you spared me the effort. :)
Just one tiny observation: you’ve left out the closing bracket on the if-condition for the second function.
Comment from spudly
Time: January 20, 2008, 12:07 pm
Jordan - You sure about that? It looks ok to me…
Comment from Ali
Time: December 17, 2007, 8:40 pm
Thanks for the code. Regarding removeClass I shrinked it to
Object.prototype.removeClass = function( className )
{
this.className = (’ ‘ + this.className + ‘ ‘).replace(’ ‘ + className + ‘ ‘, ‘ ‘);
return className;
};
Is it good?