I aways check for elements with jQuery this way:
var x = $("div.myElement");
if (x.length > 0) {
x.show();
}
But I really don’t like that if. Is there any way to do it more simple?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The answer arrives directly from the jQuery FAQ. And is always good remember: search before posting, the jQuery Documentation is so easy and whilst so complete.
Use the
lengthproperty of the jQuery collection returned by your selector:Another important thing which is also on the FAQ: it isn’t always necessary to test whether an element exists.
If you code just
$("div.myElement").show()the element will be show only if it exists (sure, uh?), and nothing will happens (with no errors) if it does not. jQuery methods are writen to not raise errors when the selector result is empty.