On Building Software

Using CSS Classes as Markers

Ka Wai Cheung
On Building Software
2 min readMar 2, 2024

--

I used to think of CSS classes only as a way to connect HTML elements to their style definitions. It wasn’t until John Resig created jQuery (in 2006!) when I saw the possibilities of classes fully realized — a way to easily reference specific elements in the DOM, and, in this case, manipulate them in the many ways JavaScript allows you to manipulate them.

There are many tools these days that focus on a particular aspect of the front-end experience so you don’t have to. For instance, a service like Appcues lets you build tooltips, guides, and tours on top of your existing product.

Of course you could code all this stuff by hand too, but it’s nice to move some of these generic front-end commodities away from the trenches of your own code.

Appcues, like most similar tools, needs to identify elements in your DOM to do the work it needs to do. You (the developer) tell it which CSS selectors on your app you need it to act upon.

In their editing tool, they make it easy for you — just aim your cursor over the specific element in question and it will deduce the selector for you. There may be multiple unique selectors for any particular element you roll over so it lets you pick the “best” selector. You might have a dynamic page that might not have the exact same structure every time, so picking the best selector isn’t always trivial.

A really simple way around this is to add additional marker classes to the elements you want Appcues (or whichever tool you use) to identify. In other words, it may just be that the element you want Appcues to apply a tooltip over is the one defined by the body > div.main > a:first-child > span selector. Or even the one uniquely defined by the #main ID.

But my preference is to add an additional class that specifically identifies the element you want Appcues to find (and otherwise has no other reason for being). A class like .appcues-tour-main-link (or whatever makes semantic sense). As in…

<span class=“my-style-class appcues-tour-main-link”>…</span>

Adding additional class names on your targeted elements does two nice things.

First, it makes the selection a lot less vulnerable to future changes (even minor ones) to the structure of your HTML.

Second, when you do make a future update that involves changing (or removing) said elements, these marker classes are like SOS flares staring you right in the face. You’ll know that the change you’re about to make can be a breaking one.

And warning signals at the moment you need to be warned — no sooner or later — are the best kind, aren’t they?

--

--

Ka Wai Cheung
On Building Software

I write about software, design, fatherhood, and nostalgia usually. Dad to a boy and a girl. Creator of donedone.com. More at kawaicheung.io.