Dennis Best
Dennis Best

Reputation: 3664

addClass to multiple distinct elements with jquery

I have some code that generates markup similar to this:

<div id="container">
  <div data-number="123">Fred</div>
  <div data-number="128">Wilma</div>
  <div data-number="129">Barney</div>
  <div data-number="123">Fred</div>
  <div data-number="123">Fred</div>
  <div data-number="129">Barney</div>
  <div data-number="111">Dino</div>
  <div data-number="008">Betty</div>
  <div data-number="123">Fred</div>
  <div data-number="123">Fred</div>
</div>

The container will have many duplicates.

The data tags are generated dynamically based on potentially thousands of data-ids. But, a particular view will likely not have more than a dozen or so unique items, so iterating over them shouldn't be a big deal.

What I want to do is add css classes to similar items in a predictable way.

  <div class="unique-item-1" data-number="123">Fred</div>
  <div class="unique-item-2" data-number="008">Betty</div>
  <div class="unique-item-3" data-number="128">Wilma</div>
  <div class="unique-item-4" data-number="129">Barney</div>
  <div class="unique-item-5" data-number="111">Dino</div>
  <div class="unique-item-1" data-number="123">Fred</div>
  <div class="unique-item-1" data-number="123">Fred</div>

You'll notice that all the Fred divs (data-number 123) get the same class (unique-item-1) added.

The goal is to have CSS that will add colors or whatever, like so:

.unique-item-1 {color:red;}
.unique-item-2 {color:pink;}
.unique-item-3 {color:green;}
.unique-item-4 {color:black;}
.unique-item-5 {color:wheat;}

I've tried using jquery's "unique"... but I guess I don't know what unique means :)

Upvotes: 0

Views: 78

Answers (1)

Balachandran
Balachandran

Reputation: 9637

Use data() attribute in jquery ,

      var getArray = [];

  $("#container").children("[data-number]").filter(function () {

      var index = $.inArray($(this).data("number"), getArray);

      if (index == -1) {
          getArray.push($(this).data("number"));
          $(this).addClass("unique-item-" + getArray.length);
      } else {
          $(this).addClass("unique-item-" + parseInt(index+1));
      }
  });

UPDATED DEMO

Upvotes: 1

Related Questions