We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

noah on 05/28/08


Tagged

css class list html xhtml DOM name


Versions (?)


List all class names used in a DOM tree


Published in: JavaScript 


Lists each CSS class name that is applied to an element within an HTML page.

Some applications suggested by this pattern are: - List class names by frequency of use. - List class names by what kind of element they are applied to. - List class names that are only used once.

  1. var allTags = document.body.getElementsByTagName('*');
  2. var classNames = {};
  3. for (var tg = 0; tg< allTags.length; tg++) {
  4. var tag = allTags[tg];
  5. if (tag.className) {
  6. var classes = tag.className.split(" ");
  7. for (var cn = 0; cn < classes.length; cn++){
  8. var cName = classes[cn];
  9. if (! classNames[cName]) {
  10. classNames[cName] = true;
  11. }
  12. }
  13. }
  14. }
  15. var classList = [];
  16. for (var name in classNames) classList.push(name);
  17. alert(classList);

Report this snippet 

You need to login to post a comment.