Does jQuery have any "find or fail" methods?

Consider the following jQuery code:

$('.child').closest('.parent').find('.sibling').hide();

      

At every step, if nothing is found, jQuery will fail (for example, if not .parent

).

Sometimes this makes sense, but often it just means that the code is not doing anything and you need to troubleshoot the problem. I would like to do something like:

$('.child').closest!('.parent')...

      

The meaning is "fails loudly if you don't find it." (Bonus if this could only be enabled during development.)

Is there anything like this in jQuery?

+3


source to share


1 answer


There isn't, but you can do it easily:

Object.keys($.fn).forEach(function(k){
  var f = $.fn[k];
  if (typeof f !=='function') return;
  $.fn['_'+k] = function(){
    var o = f.apply(this, arguments);
    if (o && 'length' in o && !o.length) throw "LOUD";
    return o;
  }
})

$("body")._find("unexisting"); // throws LOUD

      

Alternatively, you can replace the existing functions in debug mode:



if (DEBUG_MODE) {
    // let be more cautious with an explicit list this time
    ['find','closest]'].forEach(function(k){
      var f = $.fn[k]; 
      $.fn[k] = function(){
        var o = f.apply(this, arguments);
        if (o && 'length' in o && !o.length) {
          throw "LOUD"; // you shall make it a more interesting error
        }  
        return o;
      };
    });
}

      

The possibilities are endless as you run the jQuery prototype.

Now ... What is most often helpful is the fact that jQuery does not lead to empty collections. You can of course decide to integrate this code for the debug / dev session only.

+3


source







All Articles