Miguel Moura
Miguel Moura

Reputation: 39374

Check if selector is defined

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

Answers (6)

Suresh Atta
Suresh Atta

Reputation: 121998

It's an Array.

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

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Use

if(selector.length > 0) {}

Upvotes: 3

Satpal
Satpal

Reputation: 133403

You can check length

if (selector.length > 0){

}

Upvotes: 2

ComFreek
ComFreek

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

Kiran
Kiran

Reputation: 20313

You can use .length to check selector exists or not:

if (selector.length > 0){
  // do something here
}

Upvotes: 3

u_mulder
u_mulder

Reputation: 54841

Use length property:

if ( 0 < selector.length ) 

Upvotes: 3

Related Questions