Christian Heilmann

Tip: Using CSS and dynamic classes to avoid loops

Tuesday, March 14th, 2006 at 11:48 am

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
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';
}

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.

Share on Mastodon (needs instance)

Share on Twitter

My other work: