Tim
Tim

Reputation: 2257

How can I filter a list of items using jquery's .each()?

When using .each(), is there a way to filter the elements it examines?

Currently, this is what I have: given a list of elements, I only want to examine inputs.

$.each (Items, function(i, item) {
    if (item.is("input"))
        (do something)
});

Upvotes: 1

Views: 173

Answers (3)

daryl
daryl

Reputation: 15197

For learning experiences, in regards to the code in your question, here's how you would go about it:

$.each(Items, function(i, item) {
    if($(this).is('input')) {
        // do something
    }
});​

Demo: http://jsfiddle.net/g6Jsr/

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Use a if statement is ok, or you could use .filter method.

Items.filter("input").each(function() {
 // do something
});

Upvotes: 1

oezi
oezi

Reputation: 51797

yes, theres a method called .filter() - just apply this to your Items to filter the set before iterating:

$.each (Items.filter('input'), function(i, item) {
    // do something
});

another way to write this would be to call .each directly on the set (the result is the same):

Items.filter('input').each(function(i, item) {
    // do something
});

Upvotes: 4

Related Questions