Open the JavaScript console and follow these instructions to learn about jQuery's filter methods.
After running each snippet of code, refresh the page.
li
element:
$('li').first().css('color', 'red');
li
element:
$('li').eq(1).css('color', 'red');
li
element:
$('li').last().css('color', 'red');
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.
li
elements:
$('li').odd().css('color', 'red');
filter()
function to find every
third li
element:
$('li').filter(function(index) { return (index + 1) % 3 === 0; }).css('color', 'red');
has()
method to find all li
elements that have a strong
descendent element:
$('li').has('strong').css('color', 'red');
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.'); }
slice()
to find all but the first and last li
elements:
$('li').slice(1, $('li').length-1).css('color', 'red');