简体   繁体   中英

jQuery how to select div number x from a series of divs

I have a number of divs in a container like so:

<div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

I want to be able to select divs 2 and 3 using jquery and assign a class to them. I know how to use .addClass, but I don't know how I select specific divs

试试.slice方法:

$('.item').slice(1,3).addClass("CLASS");

Use $('.item').slice(1,3) to get a range like in already posted answer or alternatively, you could use as selectors :lt & :gt :

$('.item:gt(0):lt(2)')

 $('.item:gt(0):lt(2)').css('color','red'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="container"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> <div class="item">5</div> </div> 

You can use eq().

$('.container div:eq(1), .container div:eq(2)').addClass('red');

This will select item 2 and 3 and update their class in one go.

Use Jquery slice method ! please see the below codes

html codes :

<div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

javascript codes :

$('.item').slice(1,3).addClass('this');

Run jsfiddle! here " https://jsfiddle.net/gLeagw8s/ "

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