§ Adding & removing element classnames
Ok, these are just dumb. See Simpler adding & removing element classnames instead.
A couple of ways to change classnames of elements.
As usual, I'm pretty sure I stole this removeClassName function from somewhere; thank you whoever you are. Also as usual, I changed it somewhat. The addClassName function is not quite pointless, but I've never used it (not even to test); I just use the line below it.
function removeClassName(el, name) {
//don't waste time if it's not there
if(el.className.indexOf(name)<0)
return;
var i, curList, newList;
// Remove the given class name from the element's className property.
var newList = new Array();
var curList = el.className.split(" ");
for (i = 0; i < curList.length; i++)
if (curList[i] != name)
newList.push(curList[i]);
el.className = newList.join(" ");
}
function addClassName(el, name) {
//don't waste time if it's already there
if(el.className.indexOf(name)>-1)
return;
el.className += ' '+name;
}
//or just
myelement.className+=' myclassname';
In Validate form fields are filled in (additional class names) I did it a different way, but this is really to swap two known classnames:
.
.
.
var classnamei;
var requiredregex = new RegExp("required");
var highlightregex = new RegExp("highlightborder");
for (var i=0;i<aform.length;i++) {
classnamei = aform.elements[i].className;
if (requiredregex.test(classnamei) || highlightregex.test(classnamei)) {
if (aform.elements[i].value=="") {
if (focusme==undefined)
focusme=aform.elements[i];
if (requiredregex.test(classnamei)) {
aform.elements[i].className = classnamei.replace(/required/,"highlightborder");
}
}
else {
if(highlightregex.test(classnamei))
aform.elements[i].className = classnamei.replace(/highlightborder/,"required");
}
}
}
.
.
.
I'm not sure which way is "better" in general; they may each be best for certain circumstances. I also don't know which way is faster. If you expect to do this thousands of times per page, maybe you should run some timing tests.
last edited on March 27th, 2010 at 9:20 PM
- Slashback on "window.onload via double delegate function" - The makeDoubleDelegate() function is rather simple and straightforward, so I find it quite odd that Chrome can't handle it. I do…
- Joaquin Serra on "window.onload via double delegate function" - Hello, i'm using this function one year but i realized now that in Google chrome doesn't work. Have you got some solution?
- tadd on "Javascript function to add css" - thanks for the post
- Slashback on "window.onload via double delegate function" - The makeDoubleDelegate function just needs to be available, so include it once somewhere in your html file or an included javascript…
- Neil Haskins on "window.onload via double delegate function" - I don't understand exactly how this is to be used; I've just used javascript in a cut and paste manner really. Does the whole code go…