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

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: