9

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?

Hubert Kario
  • 21,314
  • 3
  • 24
  • 44

2 Answers2

15

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 length property of the jQuery collection returned by your selector:

if ($("div.myElement").length)
    $("div.myElement").show();

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.

Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
  • You is right, I really would searched the docs before... Sorry. But how can I be sure that some method will not raise errors if my selector results are empty? –  Jun 14 '11 at 00:37
  • 1
    Good answer; however, that test is added for a very important reason: there are performance gains to be had if you do not perform your operations on null collections. The proof: http://jsperf.com/jquery-check-for-null-selector-or-just-perform-method2 – Adam Terlson Jun 14 '11 at 00:40
  • To be honest, I'm not sure if all the jQuery methods behave this way. But I have a strong feeling that it's general. At least I never got an error before calling any other method, like `show`, `hide`, `animate`, `siblings`, `find`, etc.. – Erick Petrucelli Jun 14 '11 at 00:44
  • 1
    @Adam, nice test! It's a little as expected: checking before calling a method is always more performative than calling and waiting it perform the checks in there. Although not a very large performance gain, I'll keep that in mind going forward, very good! – Erick Petrucelli Jun 14 '11 at 00:54
0

You can do this :

if ($("div.myElement").is('*')) {
  ...do some stuff...
}

Or :

if ( $("div.myElement")[0] ) {
  ...do some stuff...
}

The question has been answered there and here.

Community
  • 1
  • 1
Sparkup
  • 3,686
  • 2
  • 36
  • 50
  • Please, would you explain me what this `.is("*")` means? It has good performance? –  Jun 14 '11 at 00:35