AJM
AJM

Reputation: 32490

JQuery Iterate Around DISTINCT classes on a page

I'm looking to iterate over every class defined on my html page once. I can get classnames back using Jquery, but I'm looking of way just to iterate over each individual classname once rather than for each time it appears on the page.

Upvotes: 0

Views: 446

Answers (1)

Chad Grant
Chad Grant

Reputation: 45382

Kinda odd to do this, but here ya go

<html>
<head>
   <title>Page</title>  
   <script src="jquery-1.3.2.min.js"></script>
   <script>
       $(function() {

           var classes = {};
           $("*[class]").each(function() {
               var cs = $(this).attr("class").split(/\s/g);
               for (var i = 0; i < cs.length; i++) {
                   if (!classes[cs[i]]) {
                       classes[cs[i]] = true;
                   }
               }
           });

           for (var prop in classes)
               alert(prop);
       });
</script>
</head>
   <body>

   <div class="single"></div>
   <div class="one two three"></div>
   <div class="one two three"></div>
   <div class="one two three four"></div>
   <div class="one two three five"></div>
   <div class="one two three six"></div>

   </body>
</html>

Upvotes: 1

Related Questions