views:

489

answers:

4

I want to have a line of code similar to below:

var name = $('#input-name').attr("value");

However, the id 'input-name' is not guaranteed to exist. How do I check for its existence so that the assignment does not throw an error?

+5  A: 
if ($('#input-name').length) {
  // do something
}
ScottE
@ScottE : nice tip to solve same problem for me! thx for this :) just BTW, it seems you added a trailing ; which is not necessary ?
Michael Mao
Yes, correct. Edited.
ScottE
A: 

Check for .length or .size() on the object. The select won't fail, jQuery will always return an object.

James Wiseman
A: 
var name;
if ($('#input-name').length > 0)   
name= $('#input-name').attr("value");
Niko
no need for the > 0
redsquare
A: 

In my test the assignment didn't cause an error, it simply returned undefined.

In which case the solution would be the following:

var name = $('#input-name').attr("value");
if (name) {
  // blah blah
}

Or maybe:

var name = $('#input-name').attr("value") || 'defaultValue';

... if that makes sense in your case.

wombleton