- Print
- DarkLight
How to fix CSS selector errors
On this page, you will learn how to fix the "Element not found" error caused by an incorrect CSS selector.
We assume that you already know how to:
- Read/write CSS and HTML
- Inspect HTML elements using Chrome DevTools
(To learn these first, please see the related articles section)
Common causes and solutions
To start troubleshooting, let's check the current CSS selector.
Navigate to the failed step and click to see the CSS selector.
Let's take a look at the common causes and their solutions.
1. Auto-generated CSS selector
Cause
If your CSS selector looks very long, like the below example, it implies the CSS selector was auto-generated by DevTools.
#header-navigation > div > nav > div > div.d-none.d-lg-block.flex-grow-1.h-100 > div > div > div:nth-child(3) > a
While it may be quick and easy to get a CSS selector from DevTools, it tends to be fragile if the website's structure is updated frequently.
Solution
Find an id or a combination of classes that is unique to the element.
For example:
a#link_to_login_page
or
header a.navigation.login
If no ids or classes are available, you can specify other attributes using the attribute selector like this:
a[href="./login"]
or
a img[alt="login button"]
This way, you can get a selector that's immune to updates.
2. Random ids or classnames
If your CSS selector has a random string like the below example, it implies that the ids or classnames were generated by some build tool.
a.login_ac2187y3
The random part (prefix, suffix, or entire classname/id) might change after the build.
Again, you can solve this by using the attribute selector.
a[href="./login"]
Also, if it has a consistent part (login
, in the above example), you can specify it using the wildcard syntax.
This matches the classname that contains the string "login":
a[class*="login"]
This matches the classname that start with "login":
a[class^="login"]
To learn more about attribute selectors, see MDN Web Docs - Attribute selectors.
Tips
How to confirm the "uniqueness" of your CSS selector
Follow the steps below to confirm that your selector matches only one element on the page:
- Open the DevTools window.
- Navigate to the Elements tab.
- Press Ctrl + F (Windows) or Cmd + F (Mac) to open the search text box.
- Input your CSS selector to the textbox.
- Confirm the number of the elements found by the selector.
If you are still having trouble...
Contact our Customer Success team anytime. We will help you solve this issue. 🙂
Related articles
- To learn CSS selector basics, see Using CSS selectors effectively.
- To learn how to inspect an HTML element, see Add a locator to specify an element. Official documentation in Chrome DevTools may also be helpful.
- To learn about advanced syntaxes that you can use in CSS selectors, see MDN Web Docs - Attribute selectors.