Class handling functions


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

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.


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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.