Christian Heilmann

How to get all IDs and classes used in a document?

Monday, August 4th, 2008 at 11:46 pm

This was a question from one of the attendees of my JavaScript course, and here is one solution:

 function getIDsAndClasses(elm,parent){
   var elm = elm || '*';
   if(typeof parent !== 'undefined'){
     if(typeof parent === 'string'){
       var parent = document.getElementById(parent) || document;
     }
   } else {
     var parent = document;
   }
   var elms = parent.getElementsByTagName(elm);
   var ids = [];
   var classesFilter = {};
   var i = elms.length;while(i--){
     if(elms[i].id !== ''){
       ids.push(elms[i].id);
     }
     if(elms[i].className !== ''){
       var singles = elms[i].className.split(' ');
       var j = singles.length;while(j--){
         classesFilter[singles[j]] = singles[j];
       }
     }
   }
   var classes = [];
   for(var i in classesFilter){
    classes[classes.length]=classesFilter[i];
   }
   return {ids:ids,classes:classes}
 }

You can call this method either with no parameters or filter it down by providing an element name and a parent element. The parent element could be a DOM reference or a string, both work.

In any case, the output is an object with a property of ids containing an array of ID names and a property called classes with an array of class names.

The script filters out duplicate classes and gets all applied classes – provided they are space separated.

You can see it in action (in the FireBug console) here: Test getIDsAndClasses

I tried using regex to get the IDs and classes, but that turned out to be a mess in JavaScript.

Any faster way?

Tags: , , ,

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: