How to Check an Element Exists with and Without jQuery

Abstract image used to represent Check an Element Exists with or Without jQuery
Image by iStock.

Outside of fairly rudimentary and static frontend development using (x)HTML and CSS, you're going to want to become as familiar as you can with clientside scripting via JavaScript, or indeed with jQuery (a lightweight JavaScript framework that extracts out routine functionality into an easiertouse syntax) in order to add functionality and interactivity to a page.

It is extremely common to need to check whether an element exists within your document before you try to do something programmatic with it. If you don't, and the element proves not to exist then you will run into errors in the console and risk any following JavaScript failing to run altogether.

Thankfully, it is pretty easy to check. Let's break down how you do it with jQuery first, before moving on to how you do this if you're just working with vanilla JavaScript.


Check That an Element Exists in jQuery

As I mentioned, jQuery can make some aspects of clientside development much easier when it comes to JavaScript. The code to check whether an element exists is very easy to understand:

if ($('#element').length) {
  // Element exists!
}

The jQuery object contains the elements matching #element; it is an arraylike collection, rather than an ordinary array. Its .length tells us how many matches there are. A positive count passes the if test, whilst 0 does not. Testing the collection itself would not work, because even an empty jQuery object is truthy.

It is worth mentioning here that I'm using ID as an example. You could as easily use $('.classname') or any other CSStype selector that jQuery supports. If you intend to have more than one element of the same type onpage I would highly recommend against using the same ID. IDs are after all intended to be unique within a document.


Test If an Element Exists in JavaScript

For an ID lookup without jQuery, getElementById() gives us a direct check:

var element = document.getElementById('element');

if (element !== null) {
  // Element exists!
}

document.getElementById() returns the matching element, or null when there is no match. We can therefore test element !== null; a separate typeof check is unnecessary for this return value.

Postscript

June 2026: this is a jQueryera DOM note. Checking for an element before touching it is still good defensive programming, but I would not reach for jQuery for new React or Next.js work unless I was maintaining an older front end that already depends on it.

Looking for technical direction?

I support teams that need senior judgement on React, Next.js, headless CMS architecture, performance, migrations, and technical SEO.