Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: What is returned if $('#id') doesn't match anything?

Tags:

What is returned if $('#id') doesn't match anything? I figured it would be null or false or something similar so I tried checking like so:

var item = $('#item'); if (!item){     ... } 

But that didn't work.

like image 316
Sionide21 Avatar asked May 24 '09 17:05

Sionide21


People also ask

What will be returned by the function $(' selector ')?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).

What does jQuery function return?

jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

Does jQuery return an array?

The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.

Which methods return the element as a jQuery object?

The jQuery selector finds particular DOM element(s) and wraps them with jQuery object. For example, document. getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.


Video Answer


1 Answers

You can find how many elements were matched using:

$('selector').length 

To check whether no elements were matched, use:

var item = $('#item'); if (item.length == 0) {   // ... } 
like image 64
Ayman Hourieh Avatar answered Oct 21 '22 08:10

Ayman Hourieh