Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 156 ยท The DOM

DOM Recipes

Short, reusable DOM recipes: store data on elements, test visibility and classes, detect DOM nodes, replace and remove elements, manage focus and set form actions.

Once you know how to select elements, change content and create elements, the same small questions come up in almost every project. Is this element visible? Does it have a class? Is this value even a DOM element? How do I swap a node, move focus or read the page's <meta> tags?

This lesson answers those questions with short, copy-ready recipes. Each demo writes its results into a log area on the page, so you can see exactly what each call returns.

Store data on an element

There are two good places to keep small pieces of data next to an element. The first is a data-* attribute, which shows up in the HTML and is read through element.dataset. Names are converted between kebab-case in HTML and camelCase in JavaScript, and every value is a string.

The second is a WeakMap that uses the element as its key. It can hold any value (objects, functions, numbers), nothing appears in the markup, and when the element is removed and forgotten the data is garbage-collected with it.

dataset and WeakMap

Use data-* when CSS needs to see the value (li[data-done="true"] { ... }) or when the server renders it. Use a WeakMap for anything bigger than a short string.

Check whether an element has a class or matches a selector

classList.contains() answers "does it have this class?". For anything more complex, matches() tests the element against a full CSS selector, and closest() walks up the tree to the nearest ancestor that matches.

classList, matches and closest

Check whether an element is visible

"Visible" means different things, so decide which one you need:

  • Rendered at all? Elements with display: none (or inside such a parent) have no layout box. element.checkVisibility() returns false for them, and optionally also for visibility: hidden or zero opacity with options.
  • Inside the scrolled window? Compare getBoundingClientRect() with the viewport, or use an IntersectionObserver (see Observers) when you need to react to changes.
Rendered or on screen?

The plain call checks the layout box only. Pass visibilityProperty and opacityProperty to treat visibility: hidden and opacity: 0 as hidden as well.

Check whether a value is a DOM element

Three different tests answer three different questions. instanceof Element accepts any element (including SVG), instanceof HTMLElement only HTML elements, and nodeType also covers text nodes and comments. Beware that a node from another document (for example an iframe) fails instanceof because it has a different Element constructor, so use nodeType there.

Which kind of node is it?

Replace, remove and combine

Modern methods take any mix of nodes and strings, so you rarely need parentNode.replaceChild() or appendChild() any more.

Goal Method
Replace an element old.replaceWith(a, b, "text")
Remove an element el.remove()
Empty an element el.replaceChildren()
Replace all children el.replaceChildren(...newNodes)
Add at the end or start el.append(...) / el.prepend(...)
Add before or after el.before(...) / el.after(...)

Strings you pass are inserted as text, never parsed as HTML, which makes these methods safe by default.

Replace, remove and combine

The text <b>text</b> stays literal because strings never become markup. If you really must parse a string of trusted HTML, use insertAdjacentHTML() and read the XSS lesson first.

Move focus

element.focus() moves keyboard focus. Only focusable elements (links with href, buttons, inputs and anything with tabindex) accept it. To focus a non-interactive element such as a heading after a page change, give it tabindex="-1": it becomes focusable by script but stays out of the Tab order. Pass { preventScroll: true } if the page must not jump.

focus() and activeElement

Focusing a plain paragraph does nothing, so activeElement stays on the input. This pattern (focus the new heading after content changes, or the first invalid field after a failed submit) is a big accessibility win for keyboard and screen reader users.

Read information from <meta> tags

The page's <meta> tags are ordinary elements. Query them with an attribute selector and read the content property. The document.title, document.characterSet and document.documentElement.lang properties cover other common facts.

Reading the document's metadata

Set a form's action and method

A <form> has action, method, enctype and target properties that mirror its attributes, so you can choose where it posts at run time. new FormData(form) reads its fields.

Changing where a form submits

Inside this sandbox forms never post to real servers; the submit handler prints what would be sent. For per-button targets, a submit button also accepts formaction and formmethod attributes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of element.dataset.id for <li data-id="42">?

    Every data-* value is a string. Convert with Number() when you need a number.
  2. 2. Which method finds the nearest ancestor (or the element itself) that matches a selector?

    closest() walks up the tree and returns the first match or null. matches() only tests the element itself.
  3. 3. You pass the string "<b>hi</b>" to el.append(). What appears?

    append(), prepend(), before(), after() and replaceWith() insert strings as text, so markup in them is never parsed.
  4. 4. Why does heading.focus() need tabindex="-1" on an <h3>?

    Non-interactive elements ignore focus() unless they have a tabindex. A value of -1 allows scripted focus without putting the element in the keyboard Tab order.

Summary

  • Keep small data in data-* attributes (strings, readable by CSS) and richer data in a WeakMap.
  • Test classes with classList.contains(), selectors with matches() and ancestors with closest().
  • checkVisibility() tells you if an element is rendered; getBoundingClientRect() tells you if it is on screen.
  • instanceof Element and nodeType tell DOM nodes apart from other values.
  • replaceWith(), remove(), append(), prepend() and replaceChildren() take nodes and text, never HTML.
  • Focus non-interactive elements with tabindex="-1"; read metadata with meta[name="..."] selectors.
  • A form's action and method can be changed in script; read its values with FormData.

Next: Custom Elements and Shadow DOM.