Gadgets, Computers and Nerdy Stuff
Javascript addClass/removeClass functions
While looking for compact Javascript addClass and removeClass functions, I stumbled upon http://snipplr.com/view/3561/addclass-removeclass-hasclass/.
This code allows for a few optimizations:
- The ‘match’ method is deprecated, ‘test’ should be used instead.
- The ‘addClass’ function references a non-existing ‘this’ object.
- The ‘removeClass’ function declares a new variable ‘reg’, which is unnecessary.
- The ‘removeClass’ function doesn’t handle multiple classes well.
Here is my improved version:
function hasClass(el, name) {
return new RegExp('(\\s|^)'+name+'(\\s|$)').test(el.className);
}
function addClass(el, name)
{
if (!hasClass(el, name)) { el.className += (el.className ? ' ' : '') +name; }
}
function removeClass(el, name)
{
if (hasClass(el, name)) {
el.className=el.className.replace(new RegExp('(\\s|^)'+name+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, '');
}
}
Hope this helps someone somewhere.
| Print article | This entry was posted by Arjan on March 18, 2011 at 21:29, and is filed under Javascript. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 2 years ago
Nice one.
Exactly what I was looking for.
May I post your solution here:
http://websemantics.co.uk/resources/useful_javascript_functions/
Alongside a full credit?
about 2 years ago
A couple of things though.
1. don’t use className as a variable and a property, it’s confusing.
2. there’s a surplus ; on the end of the hasClass function
thanks for the script.
about 2 years ago
@mike: Your proposed changes have been applied. Thanks.