John the Painter
John the Painter

Reputation: 2615

Add class to div with number increasing for each div

I'm wanting to add a class 'slide-number-x' to an element within each slide in a slider, with the 'x' representing the slide number in the dom.

So, for example this simple HTML markup:

<div class="slider">
    <div class="slide"><div class="slide-title"></div></div>
    <div class="slide"><div class="slide-title"></div></div>
    <div class="slide"><div class="slide-title"></div></div>
    <div class="slide"><div class="slide-title"></div></div>
</div>

Would become:

<div class="slider">
    <div class="slide slide-number-1"><div class="slide-title"></div></div>
    <div class="slide slide-number-2"><div class="slide-title"></div></div>
    <div class="slide slide-number-3"><div class="slide-title"></div></div>
    <div class="slide slide-number-4"><div class="slide-title"></div></div>
</div>

I thought this would work:

$('.slide').each(function(i){
  $(this).addClass('slide-number'i+1);
});

Any help or ideas?

Many thanks, R

Upvotes: 1

Views: 5023

Answers (5)

Ethan Gardner
Ethan Gardner

Reputation: 96

You are missing the concatenation operator. Also, the convention for incrementing a value in JavaScript is the the double plus.

$('.slide').each(function(i){
  $(this).addClass('slide-number-' + ++i);
});

Upvotes: 0

Ben Ripley
Ben Ripley

Reputation: 2145

You're + is in the wrong place... Try this. It worked for me...

$('.slide').each(function(i){
  $(this).addClass('slide-number'+i);
});

Upvotes: 0

t0ne
t0ne

Reputation: 159

This gives you what you want

$('.slide').each(function(i){
  $(this).addClass('slide-number-' + (i+1));
});

Upvotes: 0

Coronus
Coronus

Reputation: 587

It looks like it should be:

$(this).addClass('slide-number-' + (i + 1));

Upvotes: 0

Tom Walters
Tom Walters

Reputation: 15616

You forgot the concatenation operator (+), use:

$('.slide').each(function(i){
  $(this).addClass('slide-number-' + (i+1));
});

Upvotes: 9

Related Questions