I do a:
console.log($('#test'));
I know that test doesn’t exist. If I do a console.log, it doesn’t output undefined/null. Rather it ouputs something like an empty array and when I check that array it looks like it returns the jQuery object itself.
I also tried:
if ($('#test')){
//do something
}
But it still doesn’t work. I want to know whether the ID I am selecting exists on page or not. How do I do that using jQuery?
In JavaScript, objects are always truthy, so using it in that fashion will always pass the condition.
You need to check the
lengthproperty. A response of0is falsy, and will work as expected.This is unlike
document.getElementById(), which returnsnullif the element with thatidattribute does not exist.If this is confusing, you could always write a quick jQuery plugin.
You can then call
exists()on a jQuery collection, to ensure that selector has matched at least one item.