Blah Blah Woof Woof

Archived content 2005-2007

CSS selectors in Prototype are a godsend

Posted by Tim Riley Fri, 07 Sep 2007 07:51:00 GMT

This week I have been working in some parts of an app that were written a long time ago and have not been touched since.

I've had to resist the temptation to clean up all the code, but a couple of things I could not just let be.

Behold the ugly, ugly, JS code used to select checkboxes within a particular div:

/* Iterates through all users within the TBODY and checks their checkboxes */ 
function markCheckboxesForDiv(tbody, value) { 
  for (i = 0; i < tbody.childNodes.length; i++) { 
    if (tbody.childNodes[i].tagName == 'DIV') { 
      for (j = 0; j < tbody.childNodes[i].childNodes.length; j++) { 

        if (tbody.childNodes[i].childNodes[j].tagName == 'DIV') { 
          for (k = 0; k < tbody.childNodes[i].childNodes[j].childNodes.length; k++) { 

            if (tbody.childNodes[i].childNodes[j].childNodes[k].tagName == 'SPAN') { 
              for (l = 0; l < tbody.childNodes[i].childNodes[j].childNodes[k].childNodes.length; l++) { 

                if (tbody.childNodes[i].childNodes[j].childNodes[k].childNodes[l].tagName == 'INPUT') { 
                  tbody.childNodes[i].childNodes[j].childNodes[k].childNodes[l].checked = value; 
                }
              }
            }
          }
        }
      }
    }
  }
}

Apart from the obvious problems with the depply nested if statements, this code is strongly dependent on the structure of the page markup. I actually broke it while making some unrelated changes.

Here is the new version:

function markCheckboxesForDiv(divname, value) {
  $$('#' + divname + ' input[type=checkbox]').each(function(f) {
    f.checked = value;
  });
}

Much simpler, more robust and more loosely coupled thanks to the wonders of the CSS selector utility function from Prototype, dollar dollar.

Comments

(leave url/email »)