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?
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?
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.
.length>0 ? just .length is enough?.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.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.
$(".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?for loop. Think how many times for (var i=0; i<arr.length; i++) will run if arr is an empty array.