jQuery

jQuery Check Null (object exists or not) Examples

If you ever wanted to check the existence of an element of a web page or the lack of it, it can be done with  just 1 line of code. In this article, I am going to share with you an easy way to check if object/element exists or not using jQuery.

Example to Check Null (object exists or not) using jQuery

Let’s consider a simple example. In this example, I am assuming that I have div with ID “my_div”. But I want to check the existence of a div with ID “test” on body load. Our expected output is that the element should not exist.

Example: Full source code to check null (object exists or not) using jQuery

<html>
<head>
<title>jQuery - Check null objects</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>

<body>

<div id="my_div"></div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){

if( $("#test").length )
{
alert('Element exists');
}
else
{
alert('Element does NOT exist');
}

});
</script>

</body>
</html>
Simple, isn’t it?

Do you know of any other ways to use jQuery to check null object? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*