JavaScript: DOMContentLoaded

The DOMContentLoaded event fires after the HTML has been parsed and the DOM is ready to inspect or update.

What you will learn

Minimal example

document.addEventListener('DOMContentLoaded', () => {
  const title = document.querySelector('h1');
  if (title) title.classList.add('ready');
});

Use the event when the script may run before the elements it needs exist. A defer script runs after parsing, so it often can initialize directly without waiting for another event.

Common mistakes