Posted in: Using jQuery Core > Frequently Asked Questions

How do I test whether an element exists?

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

1
2
3
4
5
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:

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