Intermediate 10 min

Selecting Elements Like a Witch

Stable selectors are the difference between a test that ships and a test that breaks on Tuesday.

Selector quality determines test longevity. There is a hierarchy of stability: data-test attributes first, semantic ARIA roles second, stable class roots third, and never — never — :nth-child against a generated container.

When you inspect an element, ask: will this selector still match after the next deploy? If the class looks like '_3xKf2_button', the answer is no. If the structure depends on sibling order, the answer is no. If the selector is a data-test that the engineering team has committed to keeping, the answer is yes.

The Grimoire Shop is wired with data-test attributes on every interactive element specifically so you can practise. Open dev tools, find an element, and write a selector that would survive a redesign.

Example

// Prefer data-test, fall back to role, then to stable class.
const cta = document.querySelector('[data-test="hero-cta"]');
if (cta) cta.textContent = 'Cast your first spell';

Try this on the Shop

The best way to learn is to ship. Open this surface and apply the lesson.

Wield the Selector Wand