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.
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.
if($(".video-gallery-container").length > 0){
$(".video-gallery-container").fadeOut(300);
}
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.