- It is short.
- It is fastest compared to other locators, since in the background all
it needs to do is pick the element matching the mentioned ID.
- It’s safest, as even if the location of this element changes or
worse, even if it’s type changes, your test-script shall still be
able to locate and identify the element.
- It’s robust as any changes in the surrounding elements usually don’t
make any impact hence even if everything around the element changes
yet system shall be able to easily locate the element.
Then, why many Automation-QAs use other locators?
In an ideal world, every single element should have an ID, and every
single element on a particular page should have a unique ID, but it
may or may not be the case always.
When Auto-generated IDs are used ID-locator shall not be able to
detect. Worst case, duplicate IDs on a single page.
So what to do in this case? It totally depends upon the AUT, the patter developers followed to design the AUT, frequency of changes in UI-UX, magnitude of changes in UI-UX and last but not the least, our individual preferences.
xpath though widely used if not used the strict way, can lead to issues if the location of your element changes, but till then it can uniquely identify the tiniest object on your web-page. Also, different browsers behave differently for xpath expressions.
CSS selectors and className locators fall in same pit as xpath as whether a location may change of not, a web-application relies on its looks, and one of the key-factors for its appearance is the UI. So, CSS selectors and className locators may happen to change more often than other locators.
tagName faces the issue of having multiple objects matching the given tag, hence it won’t be a preferred option, at least not my favorite.
So, apart from ID, what you choose as a selector totally depends on the factors I mentioned above and nowadays as the browsers are getting advanced I hope the differences of execution time these locators take to search in a complex developed web-application may be comparatively negligible, making the choice even harder.