Reputation: 39374
I have the following plot function:
function plot(selector, data) {
var context = selector.get(0).getContext("2d");
var wrapper = $(selector).parent();
}
And on my javascript main file I have the following:
plot($('#pageviews'), data);
In some pages I do not the pageviews item so I get the error: TypeError: selector.get(...) is undefined
How can I check, inside the plot function, if the selector is defined?
And if it is undefined just exit the plot function.
Thank You, Miguel
Upvotes: 0
Views: 153
Reputation: 121998
Since the selector retrns an array of selected elements , Check the length
.You can use this
if ($('#pageviews').length >0 ) {
//call plot
}
or even
if( $('#pageviews').get(0) ) {
//call plot
}
Upvotes: 2
Reputation: 29424
Use this:
function plot(selector, data) {
if (!!selector.length) {
// no element was found
}
var context = selector.get(0).getContext("2d");
var wrapper = $(selector).parent();
}
This checks whether the jQuery result object does contain any elements.
Upvotes: 1