« 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
  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)
  el.className = newList.join(" ");
function addClassName(el, name) {
  //don't waste time if it's already there
  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)
      if (requiredregex.test(classnamei)) {
        aform.elements[i].className = classnamei.replace(/required/,"highlightborder");
    else {
        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


No Comments Here. Add yours below!

Add your comment

Email: (Will not be displayed - Privacy policy)
  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

On some matters, a sane man just stepped over the cliff and trusted.
Bren Cameron, Foreigner series, C.J. Cherryh