Alex Rivera | Logout

How do you check if a selector matches something in jQuery?

Asked 2008-11-18T19:13:31.130
519

In Mootools, I'd just run if ($('target')) { ... }. Does if ($('#target')) { ... } in jQuery work the same way?

Edit
Report

1 Answer

807

As the other commenters are suggesting the most efficient way to do it seems to be:

if ($(selector).length ) {
    // Do something
}

If you absolutely must have an exists() function - which will be slower- you can do:

jQuery.fn.exists = function(){return this.length>0;}

Then in your code you can use

if ($(selector).exists()) {
    // Do something
}

As answered here

answered 2008-11-18T19:20:29.900

Your Answer