Tutorial JavaScript DOM Frontend Browser APIs Developer Tools Cheat Sheet

Free JavaScript DOM Methods Cheat Sheet Online — Interactive DOM Manipulation Reference

· 18 min read

Every web page is a living tree of elements, and JavaScript DOM methods are the tools that let you read, write, rearrange, and animate that tree in real time. Whether you are building a React component, a vanilla JavaScript widget, or a browser extension, every framework ultimately translates your code into these same native DOM operations. Understanding javascript dom APIs at the platform level makes you a more effective developer regardless of which library you use day-to-day.

Our free interactive JavaScript DOM Methods cheat sheet provides eighty-plus copyable code examples organized into nine categories: Selection, Creation & Insertion, Content, Attributes & Classes, Styles & Geometry, Traversal, Events, DocumentFragment & Templates, and Advanced APIs. The Puppet Master's Dark Theater aesthetic uses deep obsidian-black backgrounds, crimson puppet-string accents, and a subtle marionette pulse animation — reinforcing the idea that every DOM method is a string pulled to make the page dance. Everything runs in your browser. No server, no signup, no data collection.

Why DOM Methods Matter

Modern frontend development often hides the DOM behind layers of abstraction. React uses a virtual DOM. Vue provides template directives. jQuery wrapped everything in a fluent chain. But every one of these tools eventually calls the same native dom methods underneath. When you understand the platform APIs directly, you gain capabilities that frameworks cannot give you.

Native DOM manipulation provides three advantages. First, you eliminate dependency overhead. A vanilla script that uses document.querySelector and element.classList adds zero kilobytes to your bundle. Second, you gain performance insight. Framework reconciliation is fast, but knowing when to use DocumentFragment for batch inserts or requestAnimationFrame for layout reads prevents reflow thrashing. Third, you understand the platform. Debugging a React component is easier when you know what element.innerHTML actually does, why event delegation reduces listener count, and how Shadow DOM encapsulates styles.

Element Selection

Before you can manipulate anything, you must find it. The modern selection API centers on document queryselector and querySelectorAll, which accept any valid CSS selector. Legacy methods like getElementById, getElementsByClassName, and getElementsByTagName remain relevant for performance-critical paths and live collection behavior.

querySelector and querySelectorAll

querySelector returns the first matching element or null. querySelectorAll returns a static NodeList of all matches. These methods accept any CSS selector including combinators, pseudo-classes, and attribute selectors.

const header = document.querySelector('header');
const navLinks = document.querySelectorAll('nav a[href^="/"]');
const firstButton = document.querySelector('.btn-primary');

getElementById

The fastest selector when you know the ID. Returns a single element or null. IDs must be unique in a document.

const app = document.getElementById('app');
if (app) app.classList.add('mounted');

matches and closest

The matches method checks whether an element would be selected by a given selector. The closest method walks up the ancestor chain and returns the nearest matching ancestor, or null if none match. These are essential for event delegation patterns.

const button = document.querySelector('.btn');
console.log(button.matches('[disabled]')); // false

const card = button.closest('.card');
console.log(card?.dataset.id);

Element Creation and Insertion

Creating elements programmatically is the foundation of dynamic interfaces. The createelement javascript API creates a bare element node, which you then configure and attach to the document tree using insertion methods.

createElement

Create a new element node with the specified tag name. The element exists in memory but is not visible until inserted into the DOM.

const div = document.createElement('div');
div.className = 'alert';
div.textContent = 'Operation completed successfully';
document.body.appendChild(div);

appendChild, insertBefore, replaceChild, removeChild

These four methods form the core of dom manipulation. appendChild adds a node as the last child. insertBefore inserts before a reference node. replaceChild swaps one child for another. removeChild detaches a child from its parent.

const parent = document.getElementById('list');
const newItem = document.createElement('li');
newItem.textContent = 'New item';

// Append to end
parent.appendChild(newItem);

// Insert before first child
parent.insertBefore(newItem, parent.firstChild);

// Replace existing child
parent.replaceChild(newItem, parent.children[1]);

// Remove child
parent.removeChild(parent.children[0]);

cloneNode

Duplicate an existing element. Pass true for a deep clone including all descendants, or false for a shallow clone of just the element itself.

const template = document.querySelector('.card');
const clone = template.cloneNode(true);
clone.querySelector('.title').textContent = 'Card 2';
document.body.appendChild(clone);

DocumentFragment for Batch Inserts

A document fragment is a lightweight container that holds nodes in memory. When appended to the DOM, the fragment empties itself and inserts its children directly. This triggers only one reflow regardless of how many elements you append.

const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const li = document.createElement('li');
  li.textContent = `Item ${i}`;
  fragment.appendChild(li);
}
document.getElementById('list').appendChild(fragment);

Element Content

Reading and writing element content is one of the most common DOM operations. Understanding the difference between element innerhtml, textcontent vs innerhtml, and innerText prevents security vulnerabilities and performance bugs.

innerHTML

innerHTML parses a string as HTML and replaces the element's children. It is powerful but dangerous: inserting untrusted data creates XSS vulnerabilities. Always sanitize user input before assignment.

// Safe: hardcoded markup
container.innerHTML = '<p class="intro">Welcome back</p>';

// Dangerous: never do this with user input
container.innerHTML = userInput; // XSS risk!

textContent

textContent sets or returns the raw text content of an element and its descendants. It is faster than innerHTML because the browser does not parse HTML. It is also safe for untrusted data since HTML tags are treated as literal text.

const el = document.querySelector('.status');
el.textContent = '<script>alert(1)</script>'; // Displayed as literal text, not executed
el.textContent = 'User: ' + username; // Safe for dynamic data

innerText

innerText is similar to textContent but respects CSS styling. It omits hidden text, triggers reflow to compute styles, and normalizes whitespace. Use textContent for performance; use innerText only when you need visually rendered text.

const hiddenEl = document.querySelector('.hidden');
console.log(hiddenEl.textContent);  // "Secret text"
console.log(hiddenEl.innerText);    // "" (hidden by CSS)

insertAdjacentHTML

Insert HTML relative to an element without replacing existing content. Four positions are supported: beforebegin, afterbegin, beforeend, and afterend.

const box = document.querySelector('.box');
box.insertAdjacentHTML('beforeend', '<span class="badge">New</span>');
box.insertAdjacentHTML('beforebegin', '<hr>');

Element Attributes and Classes

Modern DOM APIs provide clean ways to manage element state. The element classlist API replaces fragile string concatenation on className. The dataset api provides type-safe access to data-* attributes.

classList API

classList provides add, remove, toggle, and contains methods. It automatically handles whitespace and duplicate classes. This is the modern replacement for manual className string manipulation.

const btn = document.querySelector('.btn');
btn.classList.add('active', 'loading');
btn.classList.remove('disabled');
btn.classList.toggle('expanded');
console.log(btn.classList.contains('active')); // true

dataset

The dataset api maps data-* attributes to camelCase properties. data-user-id becomes dataset.userId. Values are always strings.

<div id="card" data-user-id="42" data-role="admin"></div>

const card = document.getElementById('card');
console.log(card.dataset.userId);  // "42"
console.log(card.dataset.role);    // "admin"
card.dataset.status = 'verified';  // Sets data-status="verified"

getAttribute and setAttribute

For non-data attributes, use getAttribute and setAttribute. Some attributes like id, className, and href have direct properties, but setAttribute works for any attribute including custom ones.

const link = document.querySelector('a');
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
console.log(link.getAttribute('href'));

Element Styles and Geometry

Reading element dimensions and positions is essential for animations, drag-and-drop, and layout calculations. Understanding the difference between offset, client, and scroll dimensions prevents off-by-one bugs in layout code.

getBoundingClientRect

The getboundingclientrect method returns the element's size and position relative to the viewport. The returned object includes top, right, bottom, left, width, and height. Values are in pixels and include padding and border.

const box = document.querySelector('.modal');
const rect = box.getBoundingClientRect();
console.log(rect.top, rect.left, rect.width, rect.height);

// Center an element in viewport
box.style.left = `${(window.innerWidth - rect.width) / 2}px`;
box.style.top = `${(window.innerHeight - rect.height) / 2}px`;

scrollIntoView

The scrollintoview method scrolls the element into the visible area of the browser window. The behavior: 'smooth' option enables animated scrolling. The block and inline options control alignment.

document.querySelector('#section-3').scrollIntoView({
  behavior: 'smooth',
  block: 'start'
});

// Scroll to first error in a form
const firstError = document.querySelector('.error');
firstError?.scrollIntoView({ behavior: 'smooth', block: 'center' });

offset, client, and scroll Dimensions

These three dimension families serve different purposes. offsetWidth/Height includes padding and border. clientWidth/Height includes padding but excludes border and scrollbar. scrollWidth/Height is the total scrollable area including overflow.

const el = document.querySelector('.scrollable');
console.log('Visible with border:', el.offsetWidth, el.offsetHeight);
console.log('Visible without border:', el.clientWidth, el.clientHeight);
console.log('Total scrollable:', el.scrollWidth, el.scrollHeight);
console.log('Current scroll:', el.scrollLeft, el.scrollTop);

getComputedStyle

Read the final computed styles applied to an element, including styles from CSS files, inline styles, and inherited values. Returns a read-only CSSStyleDeclaration object.

const el = document.querySelector('.box');
const styles = getComputedStyle(el);
console.log(styles.backgroundColor);
console.log(styles.fontSize);
console.log(styles.display);

DOM Traversal

Dom traversal methods let you navigate the element tree without relying on selectors. Understanding the difference between node properties and element properties prevents bugs when text nodes and comments are present.

Parent and Children

parentNode and parentElement walk upward. children returns only element nodes; childNodes includes text and comments. Use children for most traversal tasks.

const item = document.querySelector('.item');
console.log(item.parentElement);           // Parent element
console.log(item.children);                // HTMLCollection of child elements
console.log(item.childNodes);              // NodeList including text nodes
console.log(item.firstElementChild);       // First child element
console.log(item.lastElementChild);        // Last child element

Siblings

nextElementSibling and previousElementSibling skip text nodes and return only element siblings. The non-Element variants (nextSibling, previousSibling) may return text nodes.

const current = document.querySelector('.active');
const next = current.nextElementSibling;
const prev = current.previousElementSibling;
if (next) next.classList.add('highlight');

firstChild vs firstElementChild

firstChild returns any node type, including text nodes created by whitespace in your HTML. firstElementChild returns only element nodes. In modern code, prefer the Element variants.

<ul>
  <li>First</li>
  <li>Second</li>
</ul>

const ul = document.querySelector('ul');
console.log(ul.firstChild.nodeName);        // "#text" (whitespace!)
console.log(ul.firstElementChild.nodeName); // "LI"

Events

The addeventlistener API is the modern way to handle user interactions and browser events. Understanding event propagation, the event delegation pattern, and custom events separates junior developers from senior ones.

addEventListener

Attach an event handler to an element. The third argument can be an options object with capture, once, and passive flags. Use { once: true } for one-time listeners that automatically clean themselves up.

const btn = document.querySelector('.submit');
btn.addEventListener('click', handleClick);
btn.addEventListener('click', handleOnce, { once: true });

function handleClick(e) {
  console.log('Clicked!', e.target);
}

Event Delegation

Event delegation attaches a single listener to a parent element and uses event.target to determine which child was clicked. This is essential for dynamic lists where items are added and removed after the listener is attached.

document.getElementById('todo-list').addEventListener('click', (e) => {
  if (e.target.matches('.delete-btn')) {
    e.target.closest('li').remove();
  }
  if (e.target.matches('.toggle-btn')) {
    e.target.closest('li').classList.toggle('completed');
  }
});

preventDefault and stopPropagation

preventDefault prevents the browser's default action for an event. stopPropagation stops the event from bubbling up to parent elements. Use them independently based on your needs.

document.querySelector('form').addEventListener('submit', (e) => {
  e.preventDefault(); // Don't actually submit
  const data = new FormData(e.target);
  console.log(Object.fromEntries(data));
});

document.querySelector('.inner').addEventListener('click', (e) => {
  e.stopPropagation(); // Don't notify outer containers
  console.log('Inner only');
});

CustomEvent

Dispatch and listen for application-specific events. Custom events decouple components without global state managers.

// Dispatch
document.dispatchEvent(new CustomEvent('user:login', {
  detail: { userId: 42, name: 'Alice' }
}));

// Listen
document.addEventListener('user:login', (e) => {
  console.log('User logged in:', e.detail.name);
});

Document Fragment and Templates

Performance-conscious DOM code avoids repeated reflows. Document fragment and the template tag are the two primary tools for efficient bulk operations and reusable markup.

DocumentFragment Performance

As shown earlier, DocumentFragment minimizes reflow by batching insertions. This pattern is essential when rendering large lists or tables from data.

function renderItems(items) {
  const fragment = document.createDocumentFragment();
  items.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item.name;
    fragment.appendChild(li);
  });
  document.getElementById('list').appendChild(fragment);
}

The template Tag

The template tag holds HTML that is not rendered immediately. Its content is stored in a DocumentFragment accessible via .content. Clone this fragment to stamp out repeated UI patterns efficiently.

<template id="card-template">
  <article class="card">
    <h3 class="title"></h3>
    <p class="desc"></p>
  </article>
</template>

<script>
const template = document.getElementById('card-template');
const clone = template.content.cloneNode(true);
clone.querySelector('.title').textContent = 'Hello World';
clone.querySelector('.desc').textContent = 'A reusable card component';
document.body.appendChild(clone);
</script>

Advanced APIs

Beyond the core selection and manipulation APIs, modern browsers provide powerful APIs for observing changes, encapsulating components, and interacting with the browser's rendering pipeline.

Shadow DOM

Shadow dom creates an encapsulated DOM tree attached to an element. Styles inside a shadow root do not leak out, and external styles do not penetrate in. This is the foundation of Web Components.

const host = document.getElementById('widget');
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML = `
  <style>p { color: crimson; }</style>
  <p>This paragraph is encapsulated</p>
`;

Custom Elements

Custom elements let you define new HTML tags with JavaScript behavior. They integrate with the browser's element lifecycle: construction, attribute changes, DOM attachment, and removal.

class AlertBox extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<div class="alert">${this.getAttribute('message')}</div>`;
  }
}
customElements.define('alert-box', AlertBox);

// Usage in HTML
// <alert-box message="Saved successfully"></alert-box>

IntersectionObserver

The intersection observer dom API watches when elements enter or leave the viewport. It replaces expensive scroll listeners and is the standard way to implement lazy loading and infinite scroll.

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  });
}, { rootMargin: '100px' });

document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));

MutationObserver

The mutation observer dom API watches for DOM tree changes: added or removed nodes, attribute mutations, and character data changes. Use it when integrating with third-party scripts or building developer tools.

const observer = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      console.log('Added nodes:', mutation.addedNodes.length);
    }
  });
});
observer.observe(document.body, { childList: true, subtree: true });

ResizeObserver

React to element size changes without polling. More precise and efficient than listening to window resize events.

const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const { width, height } = entry.contentRect;
    console.log(`Resized to ${width}x${height}`);
  }
});
observer.observe(document.querySelector('.container'));

Range and Selection APIs

The range api and selection api let you programmatically select text and manipulate the user's text selection. Useful for text editors, highlighting, and copy-to-clipboard features.

const range = document.createRange();
range.selectNodeContents(document.querySelector('.highlight'));
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

// Programmatically select all text in an element
function selectText(el) {
  const range = document.createRange();
  range.selectNodeContents(el);
  const sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
}

Clipboard API

The clipboard api dom provides programmatic access to the system clipboard. Modern browsers support navigator.clipboard.writeText and readText with user permission.

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log('Copied to clipboard');
  } catch (err) {
    console.error('Failed to copy:', err);
  }
}

Drag and Drop API

The drag and drop api dom enables draggable elements and drop targets. Remember to call preventDefault on dragover and drop events to allow dropping.

const draggables = document.querySelectorAll('.draggable');
draggables.forEach(el => {
  el.draggable = true;
  el.addEventListener('dragstart', (e) => {
    e.dataTransfer.setData('text/plain', el.dataset.id);
  });
});

document.querySelector('.dropzone').addEventListener('drop', (e) => {
  e.preventDefault();
  const id = e.dataTransfer.getData('text/plain');
  console.log('Dropped item:', id);
});

Fullscreen API

The fullscreen api dom lets you request fullscreen mode for any element. The user must trigger the request via a gesture for security reasons.

document.getElementById('video').addEventListener('click', () => {
  const el = document.getElementById('video');
  if (el.requestFullscreen) {
    el.requestFullscreen();
  }
});

// Exit fullscreen
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') document.exitFullscreen();
});

Pro Tips and Gotchas

Even experienced developers trip over these DOM behaviors. Keep this checklist nearby when debugging layout or event issues.

  • innerHTML XSS: Never assign user input to innerHTML without sanitization. Use textContent for dynamic text, or a library like DOMPurify for HTML.
  • Live vs Static Collections: getElementsByTagName and getElementsByClassName return live HTMLCollections that update automatically. querySelectorAll returns a static NodeList. Choose based on whether you need reactivity.
  • Event Listener Memory Leaks: Remove listeners with removeEventListener when components unmount. Use { once: true } for one-shot events. Anonymous functions cannot be removed.
  • Reflow Thrashing: Reading layout properties like offsetWidth forces the browser to recalculate layout. Batch reads before writes, or use requestAnimationFrame to defer writes.
  • Whitespace Text Nodes: firstChild and childNodes include whitespace text nodes from formatted HTML. Use firstElementChild and children to skip them.
  • cloneNode Does Not Copy Event Listeners: Cloned elements lose their attached listeners. Re-attach listeners after cloning, or use event delegation on a parent.
  • template.content Is a DocumentFragment: You can clone it repeatedly. Each clone is independent and can be modified before insertion.

Related Tools and References

DOM manipulation intersects with virtually every aspect of frontend development. These related DevToolkit resources cover adjacent topics:

Conclusion

The DOM is the bridge between your JavaScript code and the visual page. Mastering javascript dom methods — from document queryselector and createelement javascript to addeventlistener and event delegation — gives you precise control over every pixel and interaction. Whether you are optimizing a React component's reflow behavior, building a vanilla widget, or debugging why an animation stutters, these APIs are the foundation.

Bookmark the JavaScript DOM Methods Cheat Sheet for instant access whenever you need to look up a traversal pattern, check the difference between textcontent vs innerhtml, or remember the closest method signature. With eighty-plus copyable examples, real-time search, and category filtering, it is the fastest way to find the exact DOM API you need.

Found this useful? Check out our free developer tools or browse more articles.