Jquery Check if Selector Null
jQuery: Handy Selector Null Check
In jQuery
, if you want to check if a selector exists or not you could check the length
property, or use the size
method.
if($('#nothing').length === 0) console.log('Nothing');
if($('#nothing').size() === 0 ) console.log('Nothing');
if($('#nothing').get(0) === undefined ) console.log('Nothing');
if($('#nothing')[0] === undefined ) console.log('Nothing');
However, by extending the fn
with a simple method we can get some nice flow.
$.fn.exists = function(){
return this.length > 0 ? this : false;
};
Then, we can use it like follows:
var $el = $('#nothing').exists() || // false
$('#something').exists() || // assign value
$('#neverHere').exists(); // never gets here.
$el.show();