Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Created May 18, 2012 09:43
Show Gist options
  • Save karlseguin/2724327 to your computer and use it in GitHub Desktop.
Save karlseguin/2724327 to your computer and use it in GitHub Desktop.
Collects all the IDs and classes from a given element down (like document.body)
function scan(parent) {
var found = {classes: {}, ids: []};
var unexamined = [parent];
while (unexamined.length > 0) {
parent = unexamined.pop();
var nodeLength = parent.childNodes.length;
for(var i = 0; i < nodeLength; ++i) {
node = parent.childNodes[i];
if (node.nodeType != 1) { continue; }
unexamined.push(node);
if (node.id !== '') { found.ids.push(node.id); }
var classes = node.getAttribute('class');
if (classes === null) { continue; }
var parts = classes.split(' ');
var length = parts.length;
for(var j = 0; j < length; ++j) {
var part = parts[j];
if (part === '') { continue; }
if (found.classes[part] === undefined) { found.classes[part] = 0; }
found.classes[part] += 1;
}
}
}
return found;
}
console.log(scan(document.body));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment