Check if element exists with jQuery selector

Asked

Viewed 24,415 times

3

Why is that,

if (typeof($("div#elementoquenãoexiste")) !== "undefined") { console.log("existe");  }

returns "existe" in the logs? Should not return undefined, taking into account that the element the selector indicates does not exist?

Or is it that being involved in a function of jQuery ($()) it comes to be defined since it has functions/properties attached to it, even if the selector points to an element that does not exist in the DOM. I’m sure?

I need a proper sense of what’s going on in this case, thank you!

  • 2

    I think you want to do if ($("div#elementoquenãoexiste").length) { console.log("existe"); }

1 answer

16


What you want to use is property .length indicating the number of elements in the jQuery object.

if ($("div#elementoquenãoexiste").length) { console.log("existe"); }

jQuery always returns an object. Be it a selector, an array, etc., it always returns an object. When you use

if (typeof($("div#elementoquenãoexiste")) !== "undefined") { console.log("existe");  }

you’re checking to see if typeof {} !== "undefined" what always gives true.

Take a look at the console of this example: https://jsfiddle.net/dnkgqycg/

What you’ll see is:

console.log($()); // []
console.log($(false)); // []
console.log($(0)); // []
console.log($([1, 2, 3])); // [1, 2, 3] 
console.log($('#eunaoexisto')); // objeto jQuery
console.log($('#eunaoexisto').length); // 0 <---- este é o unico com valor Booleano FALSE
console.log($('#euexisto')); // objeto jQuery 
console.log($('#euexisto').length); // 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.