What is the hierarchy to use 'find element' by ID, class, or xpath and so on.
Which is preferred over which?
For some elements class is being used - is that recommended?
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It only takes a minute to sign up.Sign up to join this community
My main criteria is readability and maintainability.
Speed has never been as issue for me. There's other parts of the test frameworks I use that have much more significant speed issues.
The basic idea is always 'what will it take to uniquely identify the element' with two principles:
Generally I will always use CSS over XPATH unless there is a specific reason not to.
My order is
ID If it is actually unique this is always the best bet.
Elements and class/name combinations, e.g.
Text on the page. Frequently more subject to change.
Data attributes, e.g.
DIV[data-customer='gender'] These can be an alternative to sharing js tags or layout styling.
Relative address (with xpath). This is for the (rare) occasions when I need to identify an elements on a dynamic page with changing content and then select another element relative to that.
As to whether class "is recommended?". It actually brings up a bigger issues as ID, Class and Name are all used by the following groups:
So if the automation group uses a class as part of identifying an element and then a developer or designer changes that class name, the automation breaks and vice-versa. So this is why you need to use the big picture team approach to this to agree on how to work together effectively.