ak85 ak85 - 7 months ago 19
Javascript Question

Add class to all children except first child

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/

Answer

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)

Comments