Skip to main content

How to Check if a DOM Element Exists in JavaScript

Before you can interact with a DOM element—such as reading its value, changing its style, or adding an event listener—you must first ensure that it actually exists. Attempting to access a property on a non-existent element will result in a TypeError, which can crash your script.

This guide will teach you the standard and most reliable methods for checking if an element exists. You will learn how to use document.getElementById() for single, unique elements and document.querySelector() for more flexible selections.

The Core Concept: null Means "Not Found"

The key to checking for an element's existence is understanding how DOM query methods behave when they fail to find a match. Methods that are designed to return a single element, like getElementById() and querySelector(), will return the special value null if no matching element is found.

Because null is a "falsy" value in JavaScript, you can check for it in a simple if statement.

Checking for an Element by ID

If the element you are looking for has a unique id, the document.getElementById() method is the most efficient and direct way to select it.

For example, you want to confirm that an element with a specific ID is present in the DOM.

<div id="my-element">Hello World</div>

Solution:

const element = document.getElementById('my-element');

// Because an element object is "truthy" and `null` is "falsy",
// you can use the variable directly in a conditional.
if (element) {
console.log('The element exists in the DOM.');
} else {
console.log('The element does NOT exist in the DOM.');
}
// Output: The element exists in the DOM.

// Checking for a non-existent element
const nonExistent = document.getElementById('does-not-exist');
if (nonExistent) {
// This block will not run
} else {
console.log('The second element was not found.');
}
// Output: The second element was not found.

Checking for an Element by Any CSS Selector

The document.querySelector() method is a more flexible alternative that can find the first element matching any valid CSS selector (e.g., a class, attribute, or tag name). It also returns null if no match is found.

Solution:

// Check for the first element with the class 'my-class'
const element = document.querySelector('.my-class');

if (element) {
console.log('An element with the class "my-class" exists.');
} else {
console.log('No element with that class was found.');
}
note

This is the recommended best practice for its power and consistency with modern DOM APIs.

How to Check if At Least One Element Exists

If you need to check if any elements matching a selector exist (not just one), you should use document.querySelectorAll(). This method returns a NodeList.

  • If matches are found, the NodeList will contain the elements.
  • If no matches are found, it returns an empty NodeList, not null.

To check for existence, you must check the length of the returned NodeList.

Solution:

// Get all elements with the class 'box'
const elements = document.querySelectorAll('.box');

console.log(elements.length); // e.g., 3

if (elements.length > 0) {
console.log('At least one element with the class "box" exists.');
} else {
console.log('No elements with the class "box" were found.');
}

A Common Pitfall: Running Your Script Too Early

A frequent cause of "element not found" errors is when your <script> tag is placed in the <head> of your HTML without a defer attribute. This causes the JavaScript to execute before the browser has parsed the <body> and created the DOM elements.

For example, here the index.js script runs before the div below exists:

<head>
<!-- This script runs before the div below exists -->
<script src="index.js"></script>
</head>
<body>
<div id="my-element"></div>
</body>

The solution is to ensure your script runs only after the DOM is ready.

  • Move your <script> tag: Place it just before the closing </body> tag (the most common and simplest solution).
  • Use the defer attribute: Add defer to your script tag: <script src="index.js" defer></script>.

Conclusion

Checking if a DOM element exists is a fundamental validation step in JavaScript.

  • To check for a single, specific element, use document.getElementById() or document.querySelector() and check if the result is not null.
  • To check if at least one element matching a selector exists, use document.querySelectorAll() and check if the returned .length is greater than 0.
  • Always ensure your script runs after the DOM has been loaded to avoid timing issues.