Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector vs filter()

Given the following markup

<ul class="list">
    <li>first item</li>
    ​<li class="item">second item</li>
    <li>third item</li>
</ul>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Which one these 2 expressions is better to select the second li?

$("ul li.item")

or

$("ul li").filter(".item")

This is not a very good example because it's too simple (I know I could be doing $(".item"), but in general, should I be using complex selectors or the filter function?

EDIT: If the first is more efficient, when is it appropriate / best to use the filter function?

like image 610
Hugo Migneron Avatar asked Aug 11 '10 17:08

Hugo Migneron


People also ask

Which selector is faster in jQuery?

ID and Element selector are the fastest selectors in jQuery.

What is the use of jQuery selector?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more.

What is filter method in jQuery?

The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.

Which selector is faster in JavaScript?

Ofceauce ID is a faster selector in both CSS and JavaScript.


1 Answers

The first is faster:

$("ul li.item")

This is true simply because it's equivalent, but isn't running the selector engine (Sizzle) twice to get there.

For your edit: You use .filter()...well, when you need to filter the current set, or when you need a complex filter. For example if you wanted to chain but not select the set again:

$("ul li").addClass('everyItem').filter('.item').fadeOut();

Or a complex filter:

$("ul li").filter(function() {
  return $.data(this, 'hasSomething');
}).fadeOut();

There are many uses of filter, it really depends on the situation as to what fits best. As pertains to your question though, $(selector).filter(selector)...I can't think of a case where you'd want this over a single selector if it's at all possible. The only case off the top of my head you can't do that is a complex :has() and :not() wrapping.

like image 100
Nick Craver Avatar answered Sep 29 '22 00:09

Nick Craver