Is there a 'not found' exception for jquery selector?

后端 未结 4 1418
孤街浪徒
孤街浪徒 2021-01-18 08:56

I just spent \'hours\' with the following scenario: (all back to the basics)

 $(\'#typo\').bind(\'click\' etc ...

I had a typo in the selec

相关标签:
4条回答
  • 2021-01-18 09:40

    You could use following snippet:

    UPDATED to take care of context

    DEMO

    jQuery.debug = true;
    $ = function (selector, context) {
        if (jQuery.debug && typeof selector === "string" && !jQuery(selector, context).length) 
            throw new Error("No element found!");
        return jQuery.apply(this, arguments);
    };
    
    0 讨论(0)
  • 2021-01-18 09:41

    The jquery selector returns an array of DOM Elements so if you check the length of it, if it is greater than 0 it found something, if it is equal to 0 it didn't

      if($("selector").length > 0) found;
    
    0 讨论(0)
  • 2021-01-18 09:41

    You can use the length of the returned DOM elements as a falsy and throw a new error like so:

    var el = '#el';
    
    if ($(el).length){
        // Do Stuff
    } else {
        throw new Error("Element "+el+" Doesn't Exist");
    }
    

    OR

    // Ignores Empty Selector
    if ($('#el').length){
        // Do Stuff
    }
    

    I hope this helps!

    0 讨论(0)
  • 2021-01-18 09:48
    var element = $('#typo');
    if (element.length > 0) {
        // element exists
    }
    

    Short of that, you would have to modify the jQuery source code to get that behavior.

    0 讨论(0)
提交回复
热议问题