0

I'm a little confused, suppose I do various selections, both single and multi:

$('#button1').off('handler').on('handler')
$('input[id*="my_button"]').each(function() {

But in my HTML there are no elements with IDs "button1" (Ex. 1) or any substring of "my_button" (Ex. 2).

Will there be JS errors if no elements are found, or the code will just silently not execute?

I've seen both, and I'd like to silently process/skip if there are no matching elements.

1
  • 1
    Why don't you just try it, or read the documentation, and you'll find that jQuery always returns an array-like object Commented Jan 3, 2016 at 20:48

2 Answers 2

9

No, it will not error. It will return an empty result set. Any operations attempted on it will simply be ignored.

Sign up to request clarification or add additional context in comments.

Comments

4

There is no difference between a "single" and a "multiple" selector. As far as jQuery is concerned, it is a (potentially empty) group of elements.

.on and .off, for example, will apply/remove the event handler on each of the elements in the group. If that group happens to be empty, then nothing happens.

In some ways, this is a good thing - it removes the need for manually checking it. However, I tend to see it as a problem. Let's say I write:

document.getElementById('button1').addEventListener(...);

But #button1 does not exist on the page. I get an error telling me such (sort of - "Unable to get property 'addEventListener' of undefined or null reference" is not immediately obvious but you learn to understand it) and I can resolve the problem either by fixing the absence of the desired element, or adding a check to explicitly say "it's okay if there isn't such an element".

However in jQuery you don't get that choice. Typo in your selector? The empty collection is handled just fine and events mysteriously disappear. I consider this to be a bad thing personally, but there's no way for jQuery to know whether you intended for zero, one, or hundreds of elements to match...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.