Check whether an element exists in DOM or not with jQuery
In this post, we will explore different ways of checking whether an element exists in the DOM or not with jQuery.
One of the common tasks in jQuery is checking whether an element exists in the DOM or not. For example, we may want to perform some action only if a particular element is present on the page, or avoid errors when trying to access an element that does not exist.
1. Using length property
The simplest way to check whether an element exists in the DOM or not is to use the length property of the jQuery object. The length property returns the number of elements that match the given selector. To check whether an element exists in the DOM or not, we can simply check if the length property of the jQuery object is greater than zero. Therefore, we can use a simple if statement to check whether an element exists in the DOM or not, like this:
jQuery
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($("#name").length) { alert("The element exists"); } else { alert("The element does not exist"); } }); |
HTML
|
1 |
<label>Email address: <input type="email" id="name" placeholder="Enter email"></label> |
2. Using contains() method
Another way of checking whether an element exists in the DOM or not with jQuery is by calling the static method contains() on the jQuery class. This method takes two parameters, which are the container element and the contained element, and returns true if the container element contains the contained element, and false otherwise. For example:
|
1 2 3 4 5 6 7 |
$(document).ready(function() { if ($.contains(document.body, $("#name")[0])) { alert("The element exists"); } else { alert("The element does not exist"); } }); |
Note that we have to use the [0] index to access the first element of the jQuery object, as the contains method expects a DOM element, not a jQuery object. The contains() method is useful when we want to check whether an element exists in the DOM or not within a specific context, such as within another element.
3. Using selector()[0]
If the element is present in DOM, then the first item in the jQuery object array would be defined. So, the code can be simplified to:
jQuery
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($("#name")[0]) { alert("The element exists"); } else { alert("The element does not exist"); } }); |
HTML
|
1 |
<label>Email address: <input type="email" id="name" placeholder="Enter email"></label> |
That’s all about determining whether an element exists in DOM or not with jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)