jQuery Filter Methods

Open the JavaScript console and follow these instructions to learn about jQuery's filter methods.

After running each snippet of code, refresh the page.

  1. Find the first li element:
    $('li').first().css('color', 'red');
  2. Find the second li element:
    $('li').eq(1).css('color', 'red');
  3. Find the last li element:
    $('li').last().css('color', 'red');
  4. Find all the even li elements:
    $('li').even().css('color', 'red');
    Notice that it is the odd list items that become bold. That is because JavaScript is 0-based. So, the first li element is the zeroeth, which is even.
  5. Find all the odd li elements:
    $('li').odd().css('color', 'red');
  6. Use the filter() function to find every third li element:
    $('li').filter(function(index) {
        return (index + 1) % 3 === 0;
    }).css('color', 'red');
  7. Use the has() method to find all li elements that have a strong descendent element:
    $('li').has('strong').css('color', 'red');
  8. Use the is() method to determine whether any of the elements in this page are h2 elements:
    if ($('body *').is('h2')) {
      console.log('There is an h2 element.');
    } else {
      console.log('There are no h2 elements.');
    }
  9. Use slice() to find all but the first and last li elements:
    $('li').slice(1, $('li').length-1).css('color', 'red');