bbb25
bbb25

Reputation:

How check for ID existence using jQuery?

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?

Upvotes: 30

Views: 37304

Answers (4)

ScottE
ScottE

Reputation: 21630

if ($('#input-name').length) {
  // do something
}

Upvotes: 61

wombleton
wombleton

Reputation: 8376

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.

Upvotes: 1

Niko
Niko

Reputation: 6269

var name;
if ($('#input-name').length > 0)   
name= $('#input-name').attr("value");

Upvotes: 0

Mutation Person
Mutation Person

Reputation: 30498

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

Upvotes: 3

Related Questions