Posted By

pmw57 on 09/13/12


Tagged

javascript js class remove add has


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

aaearhart
candicom
o0110o


Class handling functions


 / Published in: JavaScript
 

Standard hasClass, addClass, and removeClass functions, reworked so that jsLint is happier about them, and fixed the removeClass function so that things are trimmed after removing a class name.

  1. function hasClass(ele, cls) {
  2. return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  3. }
  4.  
  5. function addClass(ele, cls) {
  6. if (!hasClass(ele, cls)) {
  7. ele.className += ' ' + cls;
  8. }
  9. }
  10.  
  11. function removeClass(ele, cls) {
  12. if (hasClass(ele, cls)) {
  13. var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
  14. newClass = ele.className.replace(reg, ' ');
  15. ele.className = newClass.replace(/^\s+|\s+$/g, '');
  16. }
  17. }

Report this snippet  

You need to login to post a comment.