Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

exists - determine if a selector found any elements

Filed under jQuery Plugins. Published on Monday, 24th August 2009.

Releases

File / Release Date Modified Size License Link
exists 1.0 04/05/2010 0.40 kB MIT Download

Resources

Most people know you can access the length property of a jQuery object to determine how many elements were matched with a selector. The problem with this however (depending on who you talk to) is that it is not very readable.

See example 1, and then example 2, and you will see the 2nd example is much easier to read and had a much clearer intent.

Example 1

1 2 3
if ($('#does-this-exist').length) { alert('element exists'); };

Example 2

1 2 3
if ($('#does-this-exist').exists()) { alert('element exists'); };

This small plugin achieves exactly this. There is no packed version, because the plugin is so small itself. I recommend if you use it to put it inside of your main JavaScript file, as generating an additional HTTP request for such a simple plugin isn't a good idea.

Note: I know in the plugin I could of simply returned the length property, except for debugging purposes, I felt the return value of the plugin should be a Boolean.

Comments

No comments yet.

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »