Cycle99 Cycle99 - 28 days ago 10
jQuery Question

add a class to first element in array

I have a simple question about jQuery array elements...

<div id="holder">
<div class="A">A</div>
<div class="A">A</div>
<div class="A">A</div>
<div class="B">B</div>
<div class="B">B</div>
<div class="B">B</div>
<div class="B">B</div>
<div class="C">C</div>
<div class="C">C</div>
<div class="C">C</div>
<div class="C">C</div>
<div class="C">C</div>
</div>


and the JS:

var klassenarray = $("#holder").find("[class]").map(function() {
return this.className;
}).get();
alert(klassenarray);


Gives me:

A,A,A,B,B,B,B,C,C,C,C,C


Now I need to add a class called first to every element with the same className. Like that:

<div id="holder">
<div class="A first">A</div>
<div class="A">A</div>
<div class="A">A</div>
<div class="B first">B</div>
<div class="B">B</div>
<div class="B">B</div>
<div class="B">B</div>
<div class="C first">C</div>
<div class="C">C</div>
<div class="C">C</div>
<div class="C">C</div>
<div class="C">C</div>
</div>

Answer

To achieve this you can take your array, get the unique values, then loop through it and use the first() method to retrieve only the first elements with the given class. Try this:

var klassenarray = $("#holder").find("[class]").map(function() {
  return this.className;
}).get();

$.unique(klassenarray).forEach(function(c) {
  $('.' + c).first().addClass('first');
});
.first { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">
  <div class="A">A</div>
  <div class="A">A</div>
  <div class="A">A</div>
  <div class="B">B</div>
  <div class="B">B</div>
  <div class="B">B</div>
  <div class="B">B</div>
  <div class="C">C</div>
  <div class="C">C</div>
  <div class="C">C</div>
  <div class="C">C</div>
  <div class="C">C</div>
</div>