How to get all IDs and classes used in a document?
Monday, August 4th, 2008This 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?