Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a jQuery selector wasn't found?

Tags:

jquery

If I pass one selector as a parameter to a function.

// selector is an object
function(selector) {

  selector.trigger('eventHere');
}

Obviously, the event will never fire if the selector that was passed in didn't have this event, but should I do some condition checking before triggering the event? I mean:

// selector is an object
if(selector === 'matched'){
  // then fire the event
}
else{
  // do nothing
}

or just leave it...?

like image 859
qinHaiXiang Avatar asked Apr 18 '11 15:04

qinHaiXiang


1 Answers

The nice thing about jQuery is that it will not throw an exception or cause an error if the selector doesn't match. So you needn't do anything extra; this is a safe operation:

// selector **must** be a jQuery object
// the assumption here is that you've already done 
// var selector = $('selectorString'); elsewhere
// and have invoked this function with selector
function(selector){
  selector.trigger('eventHere');
}

Do note however that you must ensure that selector is a jQuery object! Otherwise, you could get an error indicating that trigger is not a function.

Edit

Adam Terlson notes in the comments "it can be worth testing if a jquery object is null or has length of 0 before execution of a function against it. Just because it won't throw an error doesn't mean that performance can't be gained by not executing it in the first place (jQuery still tries)."

There's also a jsperf test that shows that there is a discernable difference in the ops/sec for each technique (it's not time! That threw me off at first) - checking for a null/0-length jQuery object before calling the function vs. simply invoking the function.

like image 80
no.good.at.coding Avatar answered Sep 18 '22 10:09

no.good.at.coding