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?

2
  • possible duplicate of Is there an "exists" function for jQuery? Commented Jun 7, 2013 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. Commented Jun 7, 2013 at 11:20

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, @Spudley – so, there's no need to do .length>0 ? just .length is enough?
@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.
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.

2 Comments

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?
Yes. It's essentially a for loop. Think how many times for (var i=0; i<arr.length; i++) will run if arr is an empty array.
1
if($(".video-gallery-container").length > 0){ $(".video-gallery-container").fadeOut(300); } 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.