Web Development for 2010

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

Determine if a jQuery selector found any objects

Filed under jQuery / JavaScript. Published on Friday, 14th August 2009.

Sometimes, it's useful to know how many objects were matched with a jQuery selector. This is rather easy by accessing the length property of the object. This is also something that makes jQuery useful - the object returned by a selector has array like properties.

The jQuery code below will dimension a variable called allPs which will contain the number of <p> elements in the page.

Example 1

1 2 3 4 5
$(document).ready(function() {   var allPs = $('p').length;   });

We can extend this further, to solve a problem that arises early on in a jQuery programmer's career. Often, you'll want to know if an element exists, based on a selector. You can do that with the length property.

Example 2

1 2 3 4 5 6 7
$(document).ready(function() {   if ($('p.hello').length) { alert('the p tag with class "hello" has been found!'); };   });

Although this works, IMO it is not very readable. I have developed a simple plugin to make this action more readable. Using the plugin, you can simply access the exists() method to determine if the selector found any elements.

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 »