最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Will jQuery complainthrow error if it doesn't find element in selector? - Stack Overflow

programmeradmin1浏览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.

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.

Share Improve this question asked Jan 3, 2016 at 20:46 gene b.gene b. 12.1k29 gold badges138 silver badges269 bronze badges 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 – adeneo Commented Jan 3, 2016 at 20:48
Add a ment  | 

2 Answers 2

Reset to default 9

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

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...

发布评论

评论列表(0)

  1. 暂无评论