Writing good selectors means writing ones that are robust – they don’t break easily if the site is changed, or rely on items changing order or moving within the page. They also consider if stock might run out and avoid clicking things that might not work.
If you are writing a CSS Selector and don’t want to start from scratch, we recommend first quickly getting the selector by using the right-click “inspect” menu. Find the element you want to match and right click it, then Copy > “Copy Selector”.
This gives you a full path – this is handy but a bit risky. Your path will probably look a bit like this:
body > div.wrapper > div.pricing > div.main.cf >
article > a.button.bg.large-size.friendly.bs-m.iconright
Or something like:
#post-7176 > div > div.post-content.blog > a:nth-child(4)
Or perhaps it might be even longer!
However – there’s a problem. The angle bracket symbols here “>”
mean “only match an element that’s immediately inside”. These can be incredibly useful, but the problem is this is very inflexible. Websites change a lot – classes can be dynamic, elements can move around.
The “nth child” in the second example means “only match the 4th <a>
tag”.
For obvious reasons, websites change a lot over time. Small classes here and then can get tweaked, the order of elements change and so on. When you write an extremely specific selector like the above, it’s fragile and easily breaks when these changes occur.
For example, if a designer changes a class from “iconright” to be an “iconleft”, our selector would break.
It’s usually possible to take the long selectors that the Inspect view outputs and shorten / simplify them so they are more robust.
In our first example, we could shorten to
.pricing .main a.button
Assuming this matches just the element we have chosen, it’s much simpler and less dependent on the page remaining unchanged.
Often the trick is to write the selectors that are both simple but also specific enough that they don’t match other elements on the page.