testing, adding, and removing classes from an html element


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.