jquery - add a class to first element in array -
i have simple question 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 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 need add class called first every element same classname. 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>
to achieve can take array, unique values, loop through , use first()
method retrieve first elements 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>
Comments
Post a Comment