3

Why does the following code return an empty array as a result ([])?

$('#non-existing-id').first();

I thought that it should return null or undefined.

How can I check for the success then? I don't see anything about it in the documentation.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

4

Why does the following code return an empty array

It doesn't. It returns a jQuery object containing only the first match.

If there are no matches, that jQuery object contains zero elements.

I thought that it should return null or undefined.

No, the documentation says it returns a jQuery object.

How can I check for the success then?

Test the number of matches using length.

if ($('#non-existing-id').length > 0)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • In a real application I'm using the `find` function like this -- `obj.find('#some-id').first()`. If I understand you correctly, if the selector found something, it will return this object, not an array with this object. And if it didn't find anything, it will return an empty array. How can I check for the success in this case and use the resulting object after that? – FrozenHeart Feb 10 '16 at 19:43
  • "if the selector found something, it will return this object, not an array with this object. And if it didn't find anything, it will return an empty array" — It **always** returns a jQuery object. – Quentin Feb 10 '16 at 19:45
  • "How can I check for the success in this case " — Look at the code on the last line of the answer! – Quentin Feb 10 '16 at 19:45
  • How is that ugly? What would you rather see? – epascarello Feb 10 '16 at 19:53
1

$('#non-existing-id') returns an empty array since it found zero matches.

.first() returns zero results since it doesn't find any result in an empty array.

$('#non-existing-id').eq(423424); also returns an empty array [] as example.

seahorsepip
  • 4,519
  • 1
  • 19
  • 30