Find the first element that doesn't match

jQuery

jQuery unfortunately doesn't offer a method to filter for the first hit. .filter will find all that match. That's is why I made this small jQuery extension method, which will return the first element that doesn't match the filter.

$.fn.extend({ firstMismatch: function(filter) { for (var element, i = 0; element = this[i]; i++) { if (!filter.call(element)) return element; } });

It can be used in this fashion

var $required = $('.required'); var inputsValidation = function () { return $(this).val().length > 0; } var mismatch = $required.firstMismatch(inputsValidation) // mismatch is the first element that is Empty

Reference

No known

History Feb 22, 2016