eric01
eric01

Reputation: 919

In jQuery, how to test whether an element is the first of many elements of same class?

I have 3 div's:

<div class='squares' id='div1'></div>
<div class='squares' id='div2'></div>
<div class='squares' id='div3'></div>

With jQuery, I would like to apply a css property (a border-right) to all div's, except the first one.

What is the if statement that I should use? I want to use the class in the if statement (not the id's).

Thanks very much.

Upvotes: 1

Views: 69

Answers (3)

gilly3
gilly3

Reputation: 91497

Use .is() in your if statement:

if (!$(this).is(".squares:first()")) {
    // not the first square 
}

Upvotes: 2

m-r-r
m-r-r

Reputation: 555

Have you tied using :first and :not() selectors ?

I haven't tested, but the following code should do what you want:

$(".squares:not(:first)").css("border-right", "thin solid red");

Upvotes: 3

Ram
Ram

Reputation: 144689

You can use :not() and :first selectors:

$('.squares:not(:first)').addClass('border')

or:

$('.squares:not(:first)').css('border-right', 'value')

Upvotes: 5

Related Questions