Why it is important to have unique ids for page elements?

Identification of correct GUI elements present on web page (e.g. Text Box, Buttons, CheckBoxes etc.) is a prerequisite to create an automation script. Selenium provides a number of Locators to precisely locate a GUI element on the page such as: Ids, Name, XPath, CSS Selector, LinkText/Partial Link Text & Class Name. During application life cycle developers may need to change CSS classes and even the position of the element on the page. As soon as something changes, let’s say, a CSS class, if that test uses that CSS class or XPath to search for the element, the test script stops working.

What should be the preferred way to avoid problems?

Ids are the most preferred way to locate elements on a page, as each id is supposed to be unique which makes ids a very faster and reliable way to locate elements. Although the CSS class or the position of an element can be changed, a developer rarely changes its ID.

Some Common Challenges encountered by Automation Developers:

• Element doesn’t have an id and they rely on other element attributes to identify elements. In absence of unique id, sometimes identifying an element on page becomes very difficult and time consuming and also adds complexity to test scripts.

• If developers use other ways to locate elements on page, sometimes they need to tweak the script for the script to work on other browsers. It is possible to eliminate this effort by using unique ids.

• Sometimes, an element has a very unstable ID (it may be dynamically generated). In such cases developers should create any specific property for the element that can be used to identify it during test scripting as HTML5 allows creating any extra attribute on any HTML tag.

Therefore it is better to locate all elements in the HTML through the element’s unique ID (and not through their CSS class, relative position, or any other unstable information). If the element does not have an ID, it is better to give it an ID, even though it is just for testing purposes.
If we use ids to identify elements, we can reduce the cost of maintenance and focus our time on more important tasks instead of debugging false negative results.

Article written by

Please comment with your real name using good manners.

Leave a Reply