Determining whether jQuery has not found any element

JqueryCss Selectors

Jquery Problem Overview


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"));

Jquery Solutions


Solution 1 - Jquery

$('#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) { /* 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.

Solution 2 - Jquery

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
}

Solution 3 - Jquery

!$.isEmptyObject($.find('#id'))

This will return true if the element exists and false if it doesn't.

Solution 4 - Jquery

$('#my_selector').length > 0 
$('#my_selector').get(0) !== undefined
$('#my_selector')[0] !== undefined

This is the basic, now do whatever you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBardockView Question on Stackoverflow
Solution 1 - JqueryfuturaprimeView Answer on Stackoverflow
Solution 2 - JqueryJohn HartsockView Answer on Stackoverflow
Solution 3 - JquerySpasView Answer on Stackoverflow
Solution 4 - JqueryBlackjokerView Answer on Stackoverflow