Hassan Sardar
Hassan Sardar

Reputation: 4523

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

Upvotes: 1

Views: 863

Answers (2)

vals
vals

Reputation: 64244

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

Upvotes: 4

user2736012
user2736012

Reputation: 3543

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.

Upvotes: 7

Related Questions