简体   繁体   中英

Hide all Divs except last 2. Number of Divs can increase

I want to hide all the Divs except Last 2 . Number of Divs can increase in my case.

I have searched some topics, so now i became able to hide all except last 1 div.

Here is my Code so far: http://jsfiddle.net/D83ZC/11/

HTML:

<div class="container">
    <p> This is Div 1
</div>

<div class="container">
    <p> This is Div 2
</div>

<div class="container">
    <p> This is Div 3
</div>

<div class="container">
    <p> This is Div 4
</div>

<div class="container">
    <p> This is Div 5
</div>   

CSS:

.container{
    border:black 1px solid;
}

Jquery:

$('.container').not(':last').hide();

Use the .slice() method.

$(".container").slice(0, -2).hide();

This behaves the same as Array.prototype.slice , where the second index you provide may be a negative number which counts back from the end.

This will be very fast, and has the benefit of not relying on non-standard selectors included with jQuery (via Sizzle), which means the browser's native selector engine will do the initial DOM selection.

You can use the CSS3 selector nth-last-child

$('.container:nth-last-child(n+3)').css('background-color', 'red');

updated demo

This will select all items that match n+3 for n begining from 0, so this is the third, fourth, and so on; begining from the last

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