Many users have doubts about how to check if an element exists in the HTML DOM using jQuery. In a nutshell, how to check if an element exists on the page in the simplest way possible?
There are several ways to achieve this result. One of them is to check if the “length” property of the element returns a number greater than 0.
For example, if we have HTML similar to the one shown below.
1<!DOCTYPE html>
2<html>
3<head>
4 <title>Lorem ipsum dolor</title>
5 <meta charset="utf-8">
6</head>
7<body>
8 <div id="myDiv">Lorem ipsum dolor sit amet.</div>
9</body>
10</html>
And we want to check if the element “myDiv” exists in the DOM (i.e. on the page), so for that, we can use the following code.
1if ($("#myDiv").length > 0) {
2 console.log("The element exists!");
3}
Simplifying the code
Since many things in JavaScript are either true or false, the return of the “length” property can be considered true or false as well. The return is a number, 0 represents “false” and everything else represents “true”.
So we can simplify the code as follows.
1if ($("#myDiv").length) {
2 console.log("The element exists!");
3}
Even removing the comparative “> 0”, the return value remains the same.
Creating an “exists” function for jQuery
We can go a little further and add a function named “exists”. This function can be used directly with the element we want to check.
1jQuery.fn.exists = function() {
2 return ( $(this).length > 0);
3}
4
5var elementExists = $("#myDiv").exists();
6
7console.log(elementExists);
We can improve even further and prevent the method from representing a possibility of chaining. Which is not possible in this case. We will do it as follows.
1jQuery.exists = function(selector) {
2 return ( $(selector).length > 0 );
3}
4
5if ( $.exists("#myDiv") ) {
6 console.log("The element exists!");
7}
Notice that now we pass the selector as an argument to the “exists” function, instead of simulating a chain directly from the object.
Checking the existence of an HTML element using the array syntax
When we use a selector in jQuery, it returns an array of elements. If we try to access the first element of this array and it returns “undefined”, it indicates that the element in question does not exist in the DOM.
1if ( $('#myDiv')[0] ) {
2 console.log("The element exists!");
3}
As you can see, there are several ways to check the existence of an HTML element on the page. What is the best? Well, the one that solves your problem. The important thing is that your code is running and working.