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!}What this does is loop over the DOM searching for any elements that match the #element selector, compiling them into an array. When we test length, anything above 0 is considered true, which means the if statement passes and we're good to go!
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
Without jQuery, the code to achieve this check is a little longer ‑ but it's still pretty clear:
var element = document.getElementById('element');if (element != null && typeof element != 'undefined') { // Element exists!}Here, this code searches the DOM for an element with an ID that matches the selector and assigns the result to a variable. From there, we test that the variable isn't null, and that the type of that variable isn't undefined. If the variable isn't null, and has a type, then we're working with an element.