<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Blah Blah Woof Woof comments on CSS selectors in Prototype are a godsend</title>
    <link>http://vault.openmonkey.com/</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Blah Blah Woof Woof comments</description>
    <item>
      <title>"CSS selectors in Prototype are a godsend" by triley</title>
      <description>&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;I've had to resist the temptation to clean up &lt;em&gt;all&lt;/em&gt; the code, but a couple of things I could not just let be.&lt;/p&gt;

&lt;p&gt;Behold the ugly, &lt;em&gt;ugly&lt;/em&gt;, JS code used to select checkboxes within a particular div:&lt;/p&gt;

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

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

            if (tbody.childNodes[i].childNodes[j].childNodes[k].tagName == 'SPAN') { 
              for (l = 0; l &amp;lt; 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; 
                }
              }
            }
          }
        }
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Here is the new version:&lt;/p&gt;

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

&lt;p&gt;Much simpler, more robust and more loosely coupled thanks to the wonders of the CSS selector utility function from Prototype, &lt;a href="http://prototypejs.org/api/utility/dollar-dollar"&gt;dollar dollar&lt;/a&gt;.&lt;/p&gt;

</description>
      <pubDate>Fri,  7 Sep 2007 00:51:00 PDT</pubDate>
      <guid>&lt;a href="/articles/2007/09/07/css-selectors-in-prototype-are-a-godsend"&gt;CSS selectors in Prototype are a godsend&lt;/a&gt;</guid>
      <link>&lt;a href="/articles/2007/09/07/css-selectors-in-prototype-are-a-godsend"&gt;CSS selectors in Prototype are a godsend&lt;/a&gt;</link>
    </item>
  </channel>
</rss>
