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:

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: