Determine if a jQuery selector found any objects
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
$(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
$(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
Note: Your comment may require approval before it is posted to the site.