Class name handling prototype methods





2
Date Submitted Wed. Nov. 28th, 2007 1:08 PM
Revision 1 of 1
Helper HRCerqueira
Tags CSS | DOM | HTML | JavaScript
Comments 1 comments
These are some prototype methods to handle class names in html elements. As you all should know, a html element can have more than one class name.

This is part of my dom handling toolkit. Check it out and use it at will.

Cheers


Object.prototype.hasClass = function(className) {
   var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)'); //use this regexp
   return pattern.test(this.className); //to check for the class
}
 
Object.prototype.addClass = function(className) {
   if (!this.hasClass(className)) { //if the class isn't there already
      this.className += (' ' + className); //append it to the end of the class list
   }
}
 
Object.prototype.removeClass = function(className) {
   var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)'); //use this regexp
   this.className = this.className.replace(pattern, ' '); //to make a search and replace by a blank space

 


.smalltext {
   font-size: 8px;
}

.bigtext {
   font-size: 15px;
}

colorblue {
   color: blue;
}

colorred {
   color: red;
}

 


<div id="someelement" class="smalltext colorred">This is some text</div>

 


var el = document.getElementById('someelement');

if (el.hasClass('colorred'))
    el.removeClass('colorred');

el.addClass('colorblue');

//now the text in someelement is blue, but still has a size of 8px

el.removeClass('smalltext');

//now the text has the default size

el.addClass('bigtext');

//now it has 15 px


 

Hernāni Cerqueira

www.hrcerqueira.com

Comments

Comments No Object.prototype addon
Sat. Dec. 1st, 2007 2:16 PM    Helper Fordiman

Voting

Votes Down


Helper Fordiman