One of the best practice in JavaSript is to check for the existence of an element before manipulating or doing anything with it.

In jQuery, or even in JavaScript, their is no function that we can use directly to check if an element exist or not. Our workaround is to count the number of matched elements using the length method.

The size() method can also be used in jQuery while the length method will work both in native JavaScript and jQuery.

Example

<script>
    jQuery(function($) {
        var div = $('div');
		
		if(div.length > 0) {
			console.log('div element found!');
		}
    });
</script>

Try it yourself →