Is there a 'not found' exception for jquery selector?
Asked Answered
P

5

6

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

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

I had a typo in the selector, but jQuery resolves

$('#funny something out there').bind(...

without any warning.

Is it possible to tell jQuery to raise an error when your selector gets nothing?

Something like this:

 $('#typo', alert('Stupid, nothing here! like '+ '#typo))

edit

I spoke against me:

$('#typo', alert('Stupid, nothing here! like '+ '#typo))

is not a solutiuon. I have to know where the error is to extend the selector

Pro answered 16/12, 2013 at 21:52 Comment(8)
jquery doesn't know if that's a wrong selector. You can certainly check for its length $selector.length & then bind the event.Santalaceous
You can check $('#typo').length, but that's something I would do after debugging led me to wonder if my selector was wrong.Criswell
@JasonP you sayd it: after debuggingPro
@Pro So in that case, I would add console.log($('#typo')) above the line that adds the handler and see what the console says.Criswell
@JasonP - yes. you're right.Santalaceous
@all: I found the typo with these tricks/ideas, I was asking if there is a jQuery (built in) logicPro
no there isn't...jQuery will fail silently if elements in selector not foundAnnoyance
@charlietfl: ok, it is not, i suggest a 'strict' logic for jQueryPro
U
12

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);
};
Unjaundiced answered 16/12, 2013 at 22:31 Comment(3)
I suggest using this snippet, but instead of throwing an error, just logging a warning if the console exists. You can then include this as a debugging tool and just exclude it from production code.Teddi
@KevinB ya, correct. I was guessing adding just a debug boolean property could be enough. BTW, still need to check for context too, but that gives the ideaUnjaundiced
Changed it from "throw new Error(" to "console.error(" and I'm a VERY happy camper, now. This will be an enormouse time saver!! THANKSRancher
R
2
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.

Rapier answered 16/12, 2013 at 21:54 Comment(4)
hm, so this would me a sugestion for a next jQuery version :=> 'Short of that, you would have to modify the jQuery source code to get that behavior.'Pro
@Pro The fact that jQuery doesn't throw an exception is widely considered a huge benefit.Rapier
$tell_me_my_bad_things=true, could solve that, isn't it?Pro
Modifying jquery is not a good idea for maintainability. Suggest you check the length if an empty selector will cause a problem. In general there are good reasons why you may want a selector to return zero length. e.g. Binding to an element which will be added in the futureDisqualification
D
0

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;
Dextroamphetamine answered 16/12, 2013 at 21:54 Comment(1)
this code I can use as soon as i understood, and found my 'typo'Pro
D
0

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!

Dunno answered 16/12, 2013 at 21:55 Comment(1)
this code I can use as soon as i understood, and found my 'typo'Pro
C
0

A slightly improved version of the answer by @A. Wolff that also works for cases like $('.exists').find('.doesnt-exist');

(function ($) {
  // Save the original jQuery `find` method
  var originalFind = $.fn.find;

  // Override the `find` method
  $.fn.find = function (selector) {
    var result = originalFind.call(this, selector);

    // Check if the selector is a string and no elements were found
    if (typeof selector === 'string' && result.length === 0) {
      console.error(`No elements found for selector: "${selector}"`);
    }

    return result;
  };
})(jQuery);
Cytolysin answered 7/10 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.