The easiest way to check if an element exists with jQuery

When you need to know if an element exists in the DOM (Document Object Model), only uses this small code:

<script type="text/javascript">
(function($){
	$(document).on('ready', function(){
		if( $("element").length ){
			// Do something :)
		}
	});
})(jQuery);	
</script>

The length property returns the number of elements that match with our selector. For example, imagine that you have the next HTML estructure:

<div class="parent">
	<ul>
		<li><a href="#">Some link</a></li>
	</ul>
	<div class="child"></div>
</div>

If you want to know if the element with class=”child” exists, just it is necessary to do:

<script type="text/javascript">
(function($){
	$(document).on('ready', function(){
		if( $(".child").length ){
			alert("Child exists");
		}
	});
})(jQuery);	
</script>

That’s all at this moment, be happy with your code!

Alex Arriaga

 

Añade un Comentario

One comment on “The easiest way to check if an element exists with jQuery”

Leave a Reply

Your email address will not be published. Required fields are marked *