Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: select the last 4 items in the list [duplicate]

Tags:

jquery

css

list

I have a list of images/ text links,

<ul>
<li>link 1</li>
<li>link 2</li>
<li>link 3</li>
<li>link 4</li>

<li>link 5</li>
<li>link 6</li>
<li>link 7</li>
<li>link 8</li>
</ul>

and I style the list in my .css file,

li {
  float:left;
  margin:0px 5px 5px 0px; 
}

but then I want the last 4 items in the list to be displayed without the 5px space at their margin bottom. so I would like to use jQuery to select these last 4 item and change their css style to marginBottom:0px;

The problem is that this is how jQuery selects the last item:

li:last

but what about the last 4? or maybe the last 5, or 6?

Thanks.

like image 397
Run Avatar asked Jan 06 '11 17:01

Run


4 Answers

$('li').slice(-4).css('color', 'red')

Example

like image 95
Josiah Ruddell Avatar answered Nov 03 '22 13:11

Josiah Ruddell


var e = $('li').slice(-4).css('margin-bottom', '0px');    

Demo

like image 29
Rion Williams Avatar answered Nov 03 '22 13:11

Rion Williams


use :gt() As in:

var n = $('ul').size();
var lastFour = $('li:gt(' + n-5 + ')');

http://api.jquery.com/gt-selector/

like image 1
Marnix Avatar answered Nov 03 '22 13:11

Marnix


$('li').slice(-4).addClass('last-li-items');

Then in your css:

.last-li-items {
    margin-bottom:0 !important;
}
like image 1
treeface Avatar answered Nov 03 '22 12:11

treeface