I'll-Be-Back
I'll-Be-Back

Reputation: 10828

What is the correct approach to use filter()?

I am using the filter() and I am wondering is this correct approach?

Using filter, It look for matching noteid and remove the image.

$.post("monitoring_ajax.php", {
    action: "removeNote",
    noteid: noteid
}, function(data) {

    $(".noteicon").filter(function(){  
        if ($(this).data('note-id') == noteid) {
            $('img', this).remove();
        }
    });

});

Upvotes: 1

Views: 64

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240878

From the jQuery docs:

.filter():

Reduce the set of matched elements to those that match the selector or pass the function's test.

Therefore I'd suggest using the .filter() method to reduce the selected elements, and then chain additional methods on the matched elements.

In your case, you could use:

$(".noteicon").filter(function(){  
    return $(this).data('note-id') == noteid; // Returns element if true
}).find('img').remove();

If you don't modify your code, then .each() may be a better substitute for .filter() since you a merely iterating over the code:

$(".noteicon").each(function(){  
    if ($(this).data('note-id') == noteid) {
        $('img', this).remove();
    }
});

Upvotes: 5

Related Questions