Class Manipulation


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

Element.prototype functions to manipulate element classes.


Copy this code and paste it in your HTML
  1. Array.prototype.contains = function(obj) {
  2. var i = this.length;
  3. while (i--) {
  4. if (this[i] === obj) {
  5. return true;
  6. }
  7. }
  8. return false;
  9. }
  10. Element.prototype.addClass = function $_addC(clas){
  11. if(this.className && this.className !== '') { // it already has at least one class
  12. if(!this.hasClass(clas)){
  13. this.className = this.className+' '+clas;
  14. }
  15. } else { // it doesnt have any classes yet
  16. this.className = clas;
  17. }
  18. }
  19. Element.prototype.hasClass = function $_has(clas){
  20. if((this.className.split(' ')).contains(clas)) return true;
  21. return false;
  22. }
  23. Element.prototype.countClasses = function $_count(){
  24. if(!this.className) return 0;
  25. if(this.className.replace(' ') == this.className) return 1;
  26. var listOf = this.className.split(' ');
  27. return listOf.length;
  28. }
  29. Element.prototype.removeClass = function $_remove(clas){
  30. if(this.hasClass(clas)){ // make sure it has the class we want to remove
  31. if(this.countClasses() == 1) this.className = '';
  32. else {
  33. var reg = new RegExp('(\\s|^)'+clas+'(\\s|$)');
  34. this.className=this.className.replace(reg,' ');
  35. }
  36. }
  37. }
  38. Element.prototype.toggleClass = function $_toggle(clas1){
  39. if(this.hasClass(clas1)) this.removeClass(clas1);
  40. else this.addClass(clas1);
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.