What is the hierarchy to use for finding elements - ID, class, name, xpath?

  • 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?

  • 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:

    • Don't over specify the page structure - this will make the selector more robust
    • Don't under specify the element - use enough information to uniquely identify an element

    Generally I will always use CSS over XPATH unless there is a specific reason not to.

    My order is

    1. ID If it is actually unique this is always the best bet.

    2. Elements and class/name combinations, e.g. input.last_name or input[name='last_name'] or div.home_address input.street

    3. Text on the page. Frequently more subject to change.

    4. Data attributes, e.g. DIV[data-customer='gender'] These can be an alternative to sharing js tags or layout styling.

    5. 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:

    • developers
    • designers
    • automation engineers

    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.

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2