JQuery plugin to detect failed selectors

Is there a jQuery plugin that can write out when a selector returns 0 elements for troubleshooting?

I know the use .length- I look from the level of observation / analysis / diagnostics, and not at the code level. I do not want to bet .lengthon all my code.

To enter the code, let's say I have a complex selector

$('#someComplex selectorHere')...

in another part of the code, I would like to know that jQuery returns 0 for this selector.

function onFailedSelector(selectorString) {
   console.log("Failed to select "+selectorString);
}

In context: we just had a lot of errors that came up thanks to the ASP.NET naming convention, and it would be useful to know which ones were broken.

+5
source share
6 answers

Try AOP magic

jsfiddle, .

jQuery.aop.around({target: window, method: '$'},
  function(invocation) {
    var result = invocation.proceed();
    if (result.length == 0) {
      console.log('0 Result selector' + invocation.arguments[0]); 
    }
    return result;
  } 
);

, , . - AOP .

$( "selector" ), , aop .

+7

:

(function ($) {
    $.fn.test = function () {
        var t = $(this);
        if (t.length == 0) {
            console.log("Failed to select " + t.selector);
        }
    };
})(jQuery);

// Usage
$('div').test();

JSFiddle

- , jQuery, ( 25 v1.6.2): ​​

var jQuery = function (selector, context) {
    // The jQuery object is actually just the init constructor 'enhanced'
    var result = new jQuery.fn.init(selector, context, rootjQuery);
    if (!result.length && selector && console) {
        console.log("Selector not found: " + selector);
    }
    return result;
},

, , , .

+4

:

var devjQuery = function(){
    var ret = jQuery.apply(this, arguments);
    if (ret.length === 0 && typeof window.console != "undefined") {
        console.log("No Elements Selected.",arguments);
    }
    return ret;
}
devjQuery("div");
devjQuery("a");

devjQuery $ jQuery. , noConflict, jQuery $, .

Edit:

$(), , (, jQuery.pushStack).

+2

, :

function $(arg) {
    if ( jQuery(arg).length == 0) {
        console.log(arg+" fails");
    }
    return jQuery(arg)
}

, , , $("#existing_elem, #not_existing_elem) . , , . , , , :)

+2

http://sandbox.phpcode.eu/g/20c9c/1

<div><div></div></div> 

<script> 
    alert($("div").length); 
</script>

0, , divs

http://sandbox.phpcode.eu/g/20c9c/2

0

You can put the debug instruction in the jQuery file and delete it when it is done. I'm not sure if the plugin has enough power. Edit the jQuery function to count the number of results before returning the created object.

var jQuery = function( selector, context ) {
    var ret= new jQuery.fn.init( selector, context, rootjQuery );
    if(ret.length == 0 && arguments.length != 0 ) {
        console.log(ret.selector + " returned zero elements!");
    }
    return ret;
},

JSFiddle: http://jsfiddle.net/HQC5V/2/

0
source

All Articles