Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jquery can I chain .filter twice?

Tags:

jquery

Why does this work, but the second example does not?

First one works.

function someFunk() {
   $('.listOne li').filter(':odd').css('background-color', '#FFFFFF');
   $('.listOne li').filter(':even').css('background-color', '#F0F0F0');
};

Second one does not work.

function someFunk() {
   $('.listOne li').filter(':odd').css('background-color', '#FFFFFF').filter(':even').css('background-color', '#F0F0F0');
};

Can I not chain .filter() in jquery?

like image 661
Xm7X Avatar asked Oct 03 '14 20:10

Xm7X


People also ask

Can you chain jQuery functions?

With jQuery, you can chain together actions/methods. Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

Can you chain filters in JavaScript?

Filtering works hand-in-hand with two other functional Array methods from ES5, map and reduce . And thanks to the ability to chain methods in JavaScript, you can use this combination to craft very clean code that performs some pretty complex functions.


1 Answers

you can use .end() to return to the previous stack after DOM navigation methods.:

$('.listOne li').filter(':odd').css('background-color', '#FFFFFF')
.end().filter(':even').css('background-color', '#F0F0F0');
like image 198
Karl-André Gagnon Avatar answered Oct 01 '22 07:10

Karl-André Gagnon