jQuery: Detect if Selector Returns a Result

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!

Related Posts :

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials. Bookmark the permalink.