Check if element exists with jQuery selector

3

Why this,

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

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

Or, because it is involved in a jQuery function ( undefined ) it will 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. Am I right?

I need a correct notion of what is happening in this case, thank you!

    
asked by anonymous 31.01.2016 / 14:34

1 answer

9

What you want to use is the .length property that indicates 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 are checking whether typeof {} !== "undefined" is always true.

Take a look at the console in this example: link

What you will 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
    
31.01.2016 / 14:42