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?
ID and Element selector are the fastest selectors in jQuery.
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.
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.
Ofceauce ID is a faster selector in both CSS and JavaScript.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With