Course contentsShow
← Web Development
Lesson 683 of 2,98212. The Document Object ModelFree lesson

Checking if Elements Exist

Handle null return values safely and understand when selection methods return empty collections vs null.

Checking if Elements Exist

You'll learn how to safely verify that elements exist before manipulating them, avoiding common null reference errors.

When you try to select an element that doesn't exist on the page, JavaScript doesn't always behave the same way. Understanding what you get back—and when—prevents your code from crashing unexpectedly.

Understanding Null vs Empty Collections

Different selection methods return different things when no match is found:

Methods that return null:

  • document.getElementById() returns null if the ID doesn't exist
  • document.querySelector() returns null if no match is found

Methods that return empty collections:

  • document.getElementsByClassName() returns an empty HTMLCollection (length of 0)
  • document.getElementsByTagName() returns an empty HTMLCollection (length of 0)
  • document.querySelectorAll() returns an empty NodeList (length of 0)

Why This Matters

If you try to manipulate null, JavaScript throws an error and your script stops running. Think of it like trying to open a door that doesn't exist—you can't turn the handle if there's no door there!

const button = document.getElementById('submit-btn');
// If button is null, this will crash:
// button.textContent = 'Click me'; // ERROR!

// Safe approach:
if (button) {
  button.textContent = 'Click me'; // Only runs if button exists
}

Empty collections won't crash when you try to loop through them—they simply contain zero items. However, checking length before processing is still good practice.

const items = document.getElementsByClassName('list-item');
if (items.length > 0) {
  // Process items
}

Key Takeaway: Always check if elements exist before manipulating them—use truthiness checks for methods that return null, and length checks for methods that return collections.