简体   繁体   中英

jQuery select x div inside div

I want to hide() the 2nd and 3rd div with class second inside div.first

<div class="first">
    <div class="another"></div>
    <div class="second"></div>
    <div class="second"></div>  // Hide this
    <div class="second"></div> // Hide this
    <div class="second"></div>
</div>
<div class="first">
    <div class="another"></div>
    <div class="second"></div>
    <div class="second"></div> // Hide this
    <div class="second"></div> // Hide this
    <div class="second"></div>
</div>

How can I select that every 2nd and 3rd div inside first class with jquery ?

Try using .each() , .slice()

 $(".first").each(function() { $(".second", this).slice(1,3).hide() }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="first"> <div class="another"></div> <div class="second">first</div> <div class="second">second</div> // Hide this <div class="second">third</div> // Hide this <div class="second">fourth</div> </div> <div class="first"> <div class="another"></div> <div class="second">first</div> <div class="second">second</div> // Hide this <div class="second">third</div> // Hide this <div class="second">fourth</div> </div> 

You can use :lt and :gt selectors.

$('.second:gt(0):lt(2)', '.first').hide();

Fiddle

You can use nth-child for that

$('.second:nth-child(3), .second:nth-child(4)', '.first').hide();

 $('.second:nth-child(3), .second:nth-child(4)', '.first').hide(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="first"> <div class="another">1</div> <div class="second">2</div> <div class="second">3</div> <!-- Hide this --> <div class="second">4</div> <!-- Hide this --> <div class="second">5</div> </div> <div class="first"> <div class="another">1</div> <div class="second">2</div> <div class="second">3</div> <!-- Hide this --> <div class="second">4</div> <!-- Hide this --> <div class="second">5</div> </div> 

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