jQuery HTML Element How to - Select the last X items in a list








Question

We would like to know how to select the last X items in a list.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.11.0.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from  ww w.j av a  2s .com-->
    $('li:gt(-5):not(:last)').css('color','red')
});
</script>
</head>
<body>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
    <li>Item ADD</li>
  </ul>
</body>
</html>

The code above is rendered as follows: