Thursday, October 16, 2008

Function of the day: $$

For some time now, I've been a fan of prototype. I find it hard to write any sort of DOM manipulating JavaScript without first importing it.

So, I was a bit surprised to learn that I've been missing out on one of its coolest features - the $$ function.

This function allows you to iterate over arbitrary nodes in an HTML document based on some CSS specification. Say you've got a document that looks like so:

<form id='contacts'>
<ul>
 <li><input type='checkbox'/> Alice</li>
 <li><input type='checkbox'/> Bob</li>
 ...
</ul>
</form>

You can trivially get to every input input tag in the list by running the following:

$$('#contacts li input')

To mark every checkbox in the list, do:

$$('#contacts li input').each(function(i) { i.checked = true; }

What I really like about this approach is that it allows you to re-use the logic you've already setup to power your style sheets. CSS and JavaScript, using the same annotations effectively- cool, eh?

To all those that are disappointed this blog post isn't about money -- need I remind you, I'm married. Now, if the post talked about allowances...well, that's a different story...

1 comment:

  1. If you like that, you'll find that jQuery selectors are downright sexy.

    ReplyDelete