top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How do you check if an element exists or not in jQuery?

+2 votes
705 views
How do you check if an element exists or not in jQuery?
posted Jul 8, 2015 by Shivaranjini

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Use the .length property of the jQuery collection returned by your selector:

if ( $( "#myDiv" ).length ) {

    $( "#myDiv" ).show();

}

Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:

$( "#myDiv" ).show();
answer Jul 8, 2015 by Vrije Mani Upadhyay
...