Garfield
Garfield

Reputation: 1222

How to prevent jquery dot evaluation when there are no matching elements

$('#someElement').somePlugin(someArgs);

The above jquery statement produces the following error:

Uncaught TypeError: Object [object Object] has no method 'somePlugin'

I know that somePlugin does not exist in this context, but it shouldn't matter because #someElement also does not exist.

What's the best way to prevent the right side of the dot from evaluating when there are no matching elements?

Upvotes: 0

Views: 94

Answers (1)

Alain Jacomet Forte
Alain Jacomet Forte

Reputation: 4685

There are many ways, one is:

var element = $('#someElement');
element.somePlugin && element.somePlugin(someArgs);

You could also test if the plugin itself is loaded:

if ( $.fn.somePlugin ) { 
  // stuff...
}

Upvotes: 1

Related Questions