jQuery Selector How to - Select last half of list and apply css








Question

We would like to know how to select last half of list and apply css.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(function(){<!-- ww w  .j  ava2  s  .c o m-->
    var yourList = $("ul li");
    var len = yourList.length;
    yourList.filter(':gt('+ ((len/2) - 1) +')').css('color','red');
});
</script>
</head>
<body>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
  </ul>
</body>
</html>

The code above is rendered as follows: