Tip: Using CSS and dynamic classes to avoid loops
This is nothing groundbreaking, but a thing I realised when checking some of my older scripts.
When it comes to hiding a lot of elements via JavaScript and CSS we tend to loop through and apply a class to hide them:
HTML:
<div id="sections">
<div>
<h2>Section 1</h2>
[... content ...]
</div> <div>
<h2>Section 2</h2>
[... content ...]
</div> <div>
<h2>Section 3</h2>
[... content ...]
</div>
</div>
CSS:
.hide{
position:absolute;
left:-999em;
height:1px;
overflow:none;
}
JavaScript:
var s=document.getElementById('sections');
if(!s){return;}
var divs=s.getElementsByTagName('div');
for (var i=1;i<divs .length;i++){
divs[i].className='hide';
}</divs>
We can avoid this loop by using the contextual selector in CSS in conjunction with one dynamic class:
#sections.dynamic div{
position:absolute;
left:-999em;
height:1px;
overflow:none;
}
We need the dynamic class to avoid us using CSS to hide things and JavaScript to show them, which is just not safe as either of the two might not be available. Instead of the loop all we need to do is assign the class to the parent node:
JavaScript:
var s=document.getElementById('sections');
if(!s){return;}
s.className='dynamic';
In the script that should show one of the elements we apply a class that overrides the initial hiding:
#sections.dynamic div.show{
position:relative;
left:0;
height:auto;
overflow:auto;
}
This does not only mean that we spare us the looping, we also keep all the look and feel in the CSS.#


March 14th, 2006 at 2:20 pm
Great article. I recently implemented something similar in a Wordpress template. I wanted the sidebar to be collapsible, which affected several elements on the page.
Rather than implement a complex JS solution, I simply applied or removed a “nosidebar” class from the body node. The CSS handled showing/hiding the sidebar and changing the dimensions of elements around it.
I can see the technique being useful in many situations.