简体   繁体   中英

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.

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

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

or:

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

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");

Use .is() in your if statement:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM