You have probably seen snippets like document.querySelector() or document.addEventListener() fly by in forum threads. For many front-end tasks, the document object is the entry point to reading and manipulating the page. If you are piecing together how it fits with the DOM, events, and performance best practices, this is for you.
Hi all,
I keep seeing code that uses document and I am a bit confused. What is the document object in JavaScript? How is it different from window, what are the most useful APIs, and are there any best practices or pitfalls I should know when manipulating the DOM?
The document object is your JavaScript handle to the current HTML document. It implements the DOM API, letting you read and update the structure, content, and some metadata of the page in the browser. If the DOM is a tree of nodes, document is the root gateway to that tree.
windowis the global browser context. It includes timers, network APIs, and browser-level properties likelocalStorageandlocation.documentrepresents the loaded page. It gives you access to elements, selection, events, and parsing utilities.
Wait for the DOM to be ready:
document.addEventListener('DOMContentLoaded', () => {
// Safe to query and manipulate elements here
});Code language: JavaScript (javascript)
Find elements:
const title = document.querySelector('h1');
const buttons = document.querySelectorAll('button.primary'); // NodeList
const byId = document.getElementById('app');Code language: JavaScript (javascript)
Create and insert elements:
const card = document.createElement('article');
card.className = 'card';
const h2 = document.createElement('h2');
h2.textContent = 'Hello DOM';
card.append(h2);
document.body.append(card);Code language: JavaScript (javascript)
Batch DOM updates with DocumentFragment:
const frag = document.createDocumentFragment();
['One', 'Two', 'Three'].forEach(label => {
const li = document.createElement('li');
li.textContent = label;
frag.appendChild(li);
});
document.querySelector('#list').appendChild(frag);Code language: JavaScript (javascript)
Event delegation on document:
document.addEventListener('click', (e) => {
if (e.target.matches('[data-nav]')) {
e.preventDefault();
console.log('Navigate to', e.target.dataset.nav);
}
});Code language: JavaScript (javascript)
Useful properties and helpers:
document.title,document.cookie (use securely),document.referrerdocument.body,document.head,document.documentElement(the root<html>)document.activeElement,document.getSelection()document.createRange()andRangefor advanced DOM operations
- Prefer
textContentoverinnerHTMLfor untrusted data to avoid XSS. - Minimize layout thrashing. Group reads before writes, and consider
requestAnimationFramefor visual updates. - Use event delegation for lists and dynamic content to avoid many individual listeners.
- For performance, use
DocumentFragmentor templates to batch DOM inserts. - Load scripts with defer so the DOM can parse without blocking, or wait for
DOMContentLoaded.
DOM manipulation often includes creating or optimizing <img> tags. For markup tips and common pitfalls with attributes like alt, loading, and srcset, see the guide HTML image tag. If page speed is a goal, these patterns tie directly to performance budgets and Core Web Vitals, as covered in what is an optimized website.
After you have the generic DOM patterns down, you can point your <img> elements at a fast CDN and auto-optimized assets. For example:
const img = document.createElement('img');
img.loading = 'lazy';
img.alt = 'Sample optimized image';
img.width = 800;
img.src = 'https://res.cloudinary.com/demo/image/upload/f_auto,q_auto,w_800/sample.jpg';
// Optionally supply responsive candidates with srcset:
img.srcset = [
'https://res.cloudinary.com/demo/image/upload/f_auto,q_auto,w_480/sample.jpg 480w',
'https://res.cloudinary.com/demo/image/upload/f_auto,q_auto,w_800/sample.jpg 800w',
'https://res.cloudinary.com/demo/image/upload/f_auto,q_auto,w_1200/sample.jpg 1200w'
].join(', ');
img.sizes = '(max-width: 800px) 100vw, 800px';
document.querySelector('#gallery').append(img);Code language: JavaScript (javascript)
This keeps your JavaScript vendor-neutral while tapping into automatic format selection and compression behind the scenes. If you are planning asset strategy, this overview of image hosting for websites is helpful. You can also explore handy developer-facing utilities for quick conversions and checks at Cloudinary tools.
documentis your browser-side handle to the DOM. Use it to query, create, and manage nodes.- Use
DOMContentLoaded,querySelector,DocumentFragment, and event delegation to keep code robust and fast. - Avoid unsafe
innerHTMLand reduce layout thrashing by batching DOM work. - For images, combine good
<img>markup with a CDN for speed. The guides on the HTML image tag and site optimization are solid primers.
Ready to optimize your media workflow and deliver fast, beautiful pages? Create a free Cloudinary account and start building.