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.
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).
jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.
The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.
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.
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) { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With