§ 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
- Walid on "Adventures with Ubuntu 9.10 on G4 Yikes!" - I am in the same process as you. Although I still dual-boot to Windows for my ganimg leisure. My first contact with Ubuntu was way…
- Slashback on "Simpler adding & removing element classnames" - Actually, the addClassName function does what you want, pretty much the same way you suggest.
- angie on "Simpler adding & removing element classnames" - And what if I want to add a class, but keeping the csseals the element already has?I mean, I have an element with a class, let's name…
- backlinks on "Adjust iframe height to contents" - Definitely helped me.
- Slashback on "Simpler validate form fields are filled in (no additional class names)" - You are welcome!