Posted By


skatan on 08/23/07

Tagged


Statistics


Viewed 2717 times
Favorited by 9 user(s)

addClass, removeClass, hasClass


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



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 (!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};

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.