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:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: