开发者

jQuery simplest way to check if an element exists

I aways check for elements with jQuery this way:

var x = $("div.myElement");
if (x.length > 0) {
    x.show(开发者_JAVA技巧);
}

But I really don't like that if. Is there any way to do it more simple?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜