How to Check an Element Exists with and Without jQuery

Outside of fairly rudimentary and static front‑end development using (x)HTML and CSS, you're going to want to become as familiar as you can with client‑side scripting via JavaScript, or ‑ indeed ‑ with jQuery (a lightweight JavaScript framework that extracts out routine functionality into an easier‑to‑use 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 client‑side 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 array‑like 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 CSS‑type selector that jQuery supports. If you intend to have more than one element of the same type on‑page 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 jQuery‑era 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.