views:

116

answers:

2

Hi,

I'm using jQuery's selectors, especially id selector:

$("#elementId")...

How should I determine whether jQuery has found the element or not? Even If the element with the specified id doesn't exist the next statement give me: [object Object]

alert($("#idThatDoesnotexist"));
+2  A: 

$('#idThatDoesnotexist').length is what you're looking for. (If it finds nothing, this will === 0.) So your conditional statement should probably be:

if($('#id').length > 0) { /* code if found */ } else { /* code if not found */ }

You're getting an object returned from that alert because jQuery (almost) always returns the "jQuery object" when you use it, which is a wrapper for the elements jQuery's found that permits method chaining.

futuraprime
It's working! Thanks!
Bardock
You don't need the zero, $('#id').length is enough (zero == false in javascript)
David
+2  A: 

Futuraprime is right but you can shorten your syntax by doing the following:

if ($("#id").length) {
   //at least one element was found
} else {
   //no elements found
}
John Hartsock
Thanks to you, too!
Bardock