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


HTML



Edit in JSFiddle

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:

 
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


HTML



Edit in JSFiddle

That’s all about determining whether an element exists in DOM or not with jQuery.