« Blog Home

§ 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

Comments

No Comments Here. Add yours below!

Add your comment

Name:
Email: (Will not be displayed - Privacy policy)
Website:
Comments:
  random image I can't read it!
Give me a different one!
Verify Post: Input the text from the image above to verify this post (helps prevent spam)
 

« Blog Home


“...I may be completely off base, and panicking prematurely.”
“I don’t think so.  I think you’re panicking post-maturely.  In fact, if you were panicking any later it would be practically posthumously.  I’ve been panicking for days.”
Miles & Ivan, Cetaganda, Lois McMaster Bujold