Your Ad Here

Posted By

skatan on 08/23/07


Tagged

javascript


Versions (?)

Who likes this?

16 people have marked this snippet as a favorite

n00ge
lux
wesbaker
swapnilsarwe
CharlieLaw
rodi01
sarfraznawaz2005
ckayra
seanpowell
jacoborus
dotnetbug
aegony
Kerrick
guo3823538
wirenaught
tonyganch


addClass, removeClass, hasClass


 / Published in: JavaScript
 

URL: http://www.openjs.com/scripts/dom/class_manipulation.php

  1. function hasClass(ele,cls) {
  2. return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
  3. }
  4.  
  5. function addClass(ele,cls) {
  6. if (!this.hasClass(ele,cls)) ele.className += " "+cls;
  7. }
  8.  
  9. function removeClass(ele,cls) {
  10. if (hasClass(ele,cls)) {
  11. var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
  12. ele.className=ele.className.replace(reg,' ');
  13. }
  14. }
  15.  
  16. //call the functions
  17. addClass(document.getElementById("test"), "test");
  18. removeClass(document.getElementById("test"), "test")
  19. if(hasClass(document.getElementById("test"), "test")){//do something};

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Kerrick on January 14, 2011

I recommend adding this line to the end of addClass()

ele.className.replace(/ +/g,' ');

And changing this line of removeClass()

ele.className=ele.className.replace(reg,' ');

to this:

ele.className=ele.className.replace(reg,'');

Doing so will remove all the extraneous spaces.

Posted By: Ellsass on March 29, 2011

@Kerrick: You actually need to replace it with a space. If you are removing a class that falls between two other classes, replacing it with an empty string will join those other two classes.

Given: elem.className = 'one two three';

Replacing \stwo\s with an empty string results in: elem.className = 'onethree';

Instead, replace with a single space as shown in the original example, and then replace multiple spaces with a single space: elem.className = elem.className.replace(reg,' ').replace(/\s+/g,' ');

Then (in my example) you will be left with elem.className = 'one three';.

You may also want to add .replace(/^\s|\s$/,'') to trim spaces from the very beginning or end of the .className property to take care of classes that were removed from the very beginning or end of the string.

You need to login to post a comment.