CSS container class trick

October 8th, 2007

Recently I had a debugging session with one of my colleagues and I remebered a simple trick I use often.
Imagine that you have a list of items, and you want to simultaneously change them in response to a user action.

For example, what if you have this list:

<ul class="Contacts">
  <li>Andrey <span>Shchekin<span></li>
  <li>Nina <span>Philippova<span></li>
  <li>Gordon <span>Freeman<span></li>
</ul>

And you want to show/hide (expand/collapse) all spans in javascript.

One way to do this would be to go through all spans and change their className.
But that can be quite slow on large list.

The better way is to use something like addClassName (from prototype.js) on <ul>.

So you change it to <ul class="Contacts AllCollapsed"> and then apply styles to .AllCollapsed li span.

This way the browser is responsible for finding all contained elements, which should be faster.
Also, if elements are added dynamically, you do not have to process them.