jQuery checking if a selector worked or is valid

So if a jQuery selector failed to match it used to return the document at the root level of the DOM. Now it will return an empty set. What is an empty set? If you do var test = jQuery(); you’ll get the thing — an empty jQuery wrapper object that appears around every selected element when using jQuery selectors.

So, if you do $(‘#bogusId)’, you should get a jQuery object with a length of zero. I think that is the best way I have seen to tell if nothing was matched, just check for a length of zero on the result of calling something that doesn’t match.

if($(‘#bogusID’).length ==0)

OR

var myjQueryElement = $(‘#bogusID’);
if(myjQueryElement.length == 0 )

You can also use size()

See http://api.jquery.com/jQuery/

‘As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.’

Leave a Reply

Your email address will not be published. Required fields are marked *