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:
- Best: semantic attributes —
[aria-label],[role],[name],[type],[data-testid]. They rarely change, because they carry meaning. - Good: tags and their structure —
nav a,main > article. - Risky: human-readable classes —
.sidebar,.cookie-banner. - Worst: hashed classes —
.css-1a2b3c,.jsx-987. Generated at build time, changed on every deploy.
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
- MutationObserver in rules — resilience to changes over time
- Output Console as a logger — where rule signals land
- URL patterns — resilience starts with the match
Install JustZix — and write rules that do not break at the page's next deploy.
Rate this post
No ratings yet — be the first.