In Mootools, I'd just run if ($('target')) { ... }
. Does if ($('#target')) { ... }
in jQuery work the same way?
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'.
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.
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
no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length
if ( $('#someDiv').length ){ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With