There's no clear route as to how to provide testing hooks in your HTML. Here are my three suggestions for how to mark up HTML for easy testability, in the absence of a component-based framework.
From an HTML/CSS perspective, this is a style guide decision, rather than a 'best practices' one. This is the same for a lot of HTML/CSS stuff, because they were never built to be tested in this way.
My personal style guide starts here.
By this logic, it's totally OK to use
id doesn't seem the right attribute to use.
classattributes to HTML elements to tell what they are:
By this logic,
However, this approach to using classes relies on two assumptions:
- We are using Object-Oriented CSS;
- We are using class names to name HTML/CSS 'objects'.
There is a third route, which seems messy but is potentially better.
- Use a
data-testinghookattribute like this:
That last one seems fairly messy, though, and it'll make your HTML look awful (which is actually not as bad as it sounds).
Which one should I use?
My 2 cents - use suggestion number 2. This ties neatly together with my philosophy of using the class structure to define a group of elements' purpose in CSS.