|
|
|
Class name handling prototype methods
5
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
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;
}
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




You'll only find it a hassle when you go to iterate through the members of an object.
Try the below instead. Just wrap any element ID or element in $(), and it has every method you want on your HTML Elements attached to it. Prototype does something similar here.
var ElementMethods={
hasClass:function(className) {
var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)');
return pattern.test(this.className);
},
addClass:function(className) {
if (!this.hasClass(className))
this.className += (' ' + className);
},
removeClass:function(className) {
var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)');
this.className = this.className.replace(pattern, ' ');
}
}
var $X(dst,src) {for (var i in src) dst[i]=src[i];}
var $=function (a){
if (!!a.toLowerCase) a=document.getElementById(a);
$X(a,ElementMethods);
return a;
}