jQuery: Detect if Selector Returns a Result Programming 04 JUL 2009

The easiest way to check as to whether or not your jQuery selector is returning a value is to remember that the selector is simply returning an array of jQuery objects. If no matching elements are found it simply returns an empty array.

Which of course then means that you can either check the length or size() of the returned value to ensure that it is greater than 0, indicating that your selector has successfully matched on your search request.

In other words:

if $(‘#selectMyElement’).length > 0 returns true, then you know you’ve got a hit!

picking up a peach

About Craig Lotter

Software developer, husband and dad to two young ladies. Writer behind An Exploring South African. I don't have time for myself any more.