← All posts

API & helpers

Writing JS rules that survive DOM changes

You wrote a rule, it worked for a week, today it stopped. The page did not break — it just renamed a class from .btn-primary to .Button_primary_x7f3. Here is how to write rules that survive changes like that.

Why rules break

A rule clings to the DOM of a page you do not control. Every redesign, every build with a new class hash, every A/B test can shift the ground under your feet. You cannot eliminate that — you can limit it.

Rule 1 — target what is stable

Selectors from most to least durable:

Rule 2 — target by text when classes fail

Text visible to the user changes less often than CSS classes. Instead of catching a button by class, find it by content:

const btn = [...document.querySelectorAll('button')]
  .find(b => /save|submit/i.test(b.textContent || ''));

Rule 3 — always check the element exists

A rule that assumes an element is there will blow up the day it is missing — and often kill the rest of its own code. Write defensively:

const el = document.querySelector('.target');
if (el) {
  // work here
}

The ?. operator does it concisely: document.querySelector('.target')?.remove() does nothing when the element is absent — instead of throwing.

Rule 4 — let the rule shout when it gets lost

The worst failure is a silent one — the rule does not work and you do not know why. Add a signal:

const el = document.querySelector('.target');
if (!el) JUSTZIX.warn('Rule X: .target not found — page changed?');

An entry in the Output Console tells you right away it is time to fix the selector — instead of guessing.

See also

Install JustZix — and write rules that do not break at the page's next deploy.

Rate this post

No ratings yet — be the first.

Try it yourself

Install JustZix and paste any snippet from this article. Two minutes from zero to a working rule across all your devices.

Get JustZix

Features · How it works · Examples · Use cases