Check whether an Element Exists using JQuery

In JavaScript to check whether an element exist or not we can use something like this
if(document.getElementById( 'Elementid' ))

jquery element exists

But in case of jQuery to check an element exist or not the code can be written like this

if ( $( '#elementId' ).length >0 )

We can also leave the >0 and the code will simply look like this

if ( $( '#elementId' ).length )

In the code above we are using length property of the jQuery collection returned by selector.

To display the element if exist use the show() method, the complete code will look like this

if ( $( "#elementId" ).length ) {
$( "#elementId" ).show();

so as we can see that jQuery make the code a bit shorter than javascript.

Leave a Comment