Posted By

jatkins on 07/09/10


Tagged

css class elements DOM classes


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

okmores


Add and remove CSS classes from elements


 / Published in: JavaScript
 

Public domain. find_index is required because not all versions of IE support Array.indexOf.

  1. function get(elmnt) {
  2. return document.getElementById(elmnt);
  3. }
  4.  
  5. function find_index(array, string) {
  6. var i = 0;
  7. for(i=0;i<array.length;i++) {
  8. if(array[i]==string) break;
  9. }
  10. return array[i] == string ? i : -1;
  11. }
  12.  
  13. function add_class(elmnt, new_class) {
  14. classes = get(elmnt).className.split(' ');
  15. if(find_index(classes, new_class)==-1) { // new_class is not present
  16. classes[classes.length] = new_class;
  17. get(elmnt).className = classes.join(' ');
  18. }
  19. }
  20.  
  21. function remove_class(elmnt, class_to_remove) {
  22. classes = get(elmnt).className.split(' ');
  23. class_index = find_index(classes, class_to_remove);
  24. if(class_index!=-1) { // class_to_remove is present
  25. classes.splice(class_index, 1);
  26. get(elmnt).className = classes.join(' ');
  27. }
  28. }

Report this snippet  

You need to login to post a comment.