Posted By

jambalaya on 01/20/09


Tagged

css class hasclass addclass removeclass


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jambalaya


testing, adding, and removing classes from an html element


 / Published in: JavaScript
 

  1. function cssRegex(c) {
  2. return new RegExp('(?:\\s|^)' + c + '(?:\\s|$)');
  3. }
  4.  
  5. function hasClass(e,c) {
  6. return e.className.match(cssRegex(c));
  7. }
  8.  
  9. function addClass(e,c) {
  10. if (!hasClass(e,c)) {
  11. e.className += ' '+c;
  12. return true;
  13. }
  14. return false;
  15. }
  16.  
  17. function removeClass(e,c) {
  18. if (hasClass(e,c)) {
  19. e.className=e.className.replace(cssRegex(c),' ');
  20. return true;
  21. }
  22. return false;
  23. }

Report this snippet  

You need to login to post a comment.