0

I want to do this with jQuery

if $(".video-gallery-container") exists {
$(".video-gallery-container").fadeOut(300);
} 

What's the proper way for checking for existence of an element with jQuery?

KeithRules
  • 207
  • 1
  • 4
  • 14
  • possible duplicate of [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – Felix Kling Jun 07 '13 at 11:18
  • 1
    You don't have to check whether element exists or not, jQuery doesn't throw error if element doesn't exists. – Ram Jun 07 '13 at 11:20

4 Answers4

3

jQuery provides the .length property for exactly this purpose:

if($(".video-gallery-container").length) {
    //.....
}

However, in your case you don't really need to worry about it: Just do the fadeOut without testing, because the fadeOut will only be applied to elements that match the selector; if there aren't any elements that match, the fadeOut won't be applied, but there won't be any errors.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • Thank you, @Spudley – so, there's no need to do `.length>0` ? just `.length` is enough? – KeithRules Jun 07 '13 at 11:21
  • @KeithRules - just `.lenth` is sufficient because of the way javascript tests truthy values. But as I said, you don't even need to do that; the whole `if()` test isn't required at all in the example you've given. – Spudley Jun 07 '13 at 11:23
2

You don't need to. If a selection is empty, any jQuery function called on it will simply fail to do anything:

$(".video-gallery-container").fadeOut(300);

That is all you need do.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • What if I have it as a function: `$(".video-gallery-container").fadeOut(300, function() { // some code` - if there's bo video-gallery-container, I'm assuming it will prevent the inside code from being executed, no? – KeithRules Jun 07 '13 at 11:23
  • Yes. It's essentially a `for` loop. Think how many times `for (var i=0; i – lonesomeday Jun 07 '13 at 11:24
1
if($(".video-gallery-container").length > 0){
  $(".video-gallery-container").fadeOut(300);
} 
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1
if($(".video-gallery-container").length > 0){  
  $(".video-gallery-container").fadeOut(300); 
}

Also you need not check for existence. jQuery will only add fadeOut if the element exists, otherwise it will not do anything. no error will be produced.

Nagarjun
  • 2,346
  • 19
  • 28