Reputation: 4264
I have some html where I want to add a class to all children except the first child.
<div class="test">
<div class="different">title</div>
<div class="same">a</div>
<div class="same">b</div>
<div class="same">c</div>
</div>
with the below js
<script>
$(".test").children().each(function(i) {
$(this).addClass("eg_" + (i+1));
});
</script>
see this fiddle
http://jsfiddle.net/aaronk85/HaH2y/
I want every child div of test except the first one to get the class "eg_" + (i+1) and I can't seem to get this working?
I have seen a few similar examples see the eg below but can't quite work it out from this. Where have I gone wrong here?
http://jsfiddle.net/aaronk85/y9bEG/11/
Upvotes: 3
Views: 4976
Reputation: 382102
Use gt to filter and a callback to set the precise class :
$('.test > div:gt(0)').addClass(function(i){
return 'eg_'+(i+2);
});
(it's not clear in your question if you need i
, i+1
or i+2
)
Upvotes: 7
Reputation: 866
## This code can help answer, and I completed my friends
##
<div id="list3">
<ul class="NewFilm">
<li>test1</li>
<li>test2</li>
<li>test3</li>
<li>test4</li>
<li>test5</li>
</ul>
</div>
<script>
$("li:lt(5)").addClass("eg_1");
</script>
<style>
.eg_1, .eg_2, .eg_3 {color:red;}
</style>
http://jsfiddle.net/moslem68/oo907b6s/1/
Upvotes: 0
Reputation: 5599
try this:
$(".test").children().each(function(i) {
if (i>0) {
$(this).addClass("eg_" + (i));
} else {
i++;
}
});
Upvotes: 0
Reputation: 22619
Try checking index
<script>
$(".test").children().each(function(i) {
if(i!=0){ // check the first index and add
$(this).addClass("eg_" + (i+1));
}
});
</script>
Upvotes: 2