§ 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
- 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!
- humour on "Simpler validate form fields are filled in (no additional class names)" - thanks for the script !
- Slashback on "Simpler validate form fields are filled in (no additional class names)" - Thank you. I'm glad it helped!
- buy site on "Javascript function to add css" - Well, i have faced this problem a lot of times and now i got how to add CSS to my java script. I bookmarked your page and will come…