ak85 ak85 - 11 months ago 35
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>

with the below js

$(".test").children().each(function(i) {
$(this).addClass("eg_" + (i+1));

see this fiddle


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?



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)