jquery if exists code example

Example 1: jquery check if element exists

// Check if an element currently exists
if ($('#element').length) {

}

Example 2: jquery check if exist

if ( $( "#myDiv" ).length ) {
 
    $( "#myDiv" ).show();
 
}

Example 3: Is there an “exists” function for jQuery

if ($(selector).length)

Example 4: jquery check if element still exists

$(function() {
    var $button = $(".the_button");
    alert (isStale($button));
    $button.remove();
    alert (isStale($button));
});
    
function isStale($elem)
{
    return $elem.closest("body").length > 0;
};

Example 5: jQuery exists function

if ($("#myElementID").length){
   //I exist
}