Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 224
One Crayon Avatar asked Nov 18 '08 19:11

One Crayon


People also ask

Is jQuery a selector?

The is( selector ) method checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. If no element fits, or the selector is not valid, then the response will be 'false'.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.


2 Answers

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

like image 155
Pat Avatar answered Oct 06 '22 01:10

Pat


no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){  } 
like image 45
redsquare Avatar answered Oct 05 '22 23:10

redsquare