Is it possible what I have mentioned in the title?
I would like to use this for checking existence of an element like so:
if($('#item')){...}
Any ideas?
That’s the code where I use it:
if($('#auto_redirect_in_3_s').length)//I "wished" $('#auto_redirect_in_3_s')
{
var timer = setTimeout("document.location.href = index_url;",3000);
}
description:
If I put in php code it means that the page have to redirect in 3 s.
No. The
jQueryfactory function (aliased as$) returns an instance of a jQuery collection object–even when the selection didn’t match anything. If the selector did not match, the collection is empty, but it’s still an object so it evaluates to true. You must check.lengthto see if you got anything.Such checks for
.length, however, are usually unnecessary given how jQuery works and are often a sign of poor logic or a misunderstanding of jQuery. So if you post your code, we can probably help clean it up.Update:
Ok, your updated question provided the following code:
What you’re doing isn’t terrible and could be considered an Ok usage of
.length. Allow me, however, to show you a few other ways of accomplishing the same thing. I am not saying you should do any of the following, just showing there are multiple ways to skin a cat, and hopefully show you a little more jQuery usage in some of the examples.If you’re stuck redirecting a page from the client side instead of with an HTTP header, the best way to accomplish it is with a
metatag:If you desire to keep it in JS you could avoid doing it based on the presence of an element, but on the value held by some input:
Or, with a JSON encoded value in an input (or a data attr on an element):
Going back to your version of looking for the presence of an element, you could do the following if you wanted to avoid using
.lengthand make use of jQuery’s chaining: