The Issue

Over the course of your automation development, you may encounter an element without an attribute to reference. Meaning, what you would normally use to identify a browser element in a Ruby & Watir-Webdriver command (such as an id) would be unavailable to use, or simply not present in the HTML. In this case, we can use an index to click the element for us.

The Answer

By utilizing indexes, we can leverage the parent element to click one of the child elements. The :index will use a number, going by order of elements from top to bottom. Here is what an example command would look like:

The parent link is being passed through, to the child span, at which point the browser will click the element. Even without a parent element, we can utilize :index, as seen below:

In the above example, the browser will look through all inputs, clicking the 5th one down on the page. If the element you are trying to interact with has no parent to reference through, this is a viable method to find it.

The Code

Lets use :index to click checkboxes and radio buttons on the Watir-Webdriver Demo page:

The Result

We will save the automated script. and run it from the command line. Here are the resulting steps:

  • Browser opens
  • Browser navigates to the Watir Webdriver Demo URL
  • Browser clicks on the third page input using index
  • The ‘Both’ radio button is selected, and validated
  • Browser clicks on the sixth page input using index
  • The 1.9.2 radio button is selected, and validated

Here are the results in our command line:

We confirm our browser elements are correctly checked/selected.

We confirm our browser elements are correctly checked/selected.

 

 

 
 

The Takeaway

Becoming comfortable with using the index command to interact with browser elements will allow you to tackle a multitude of issues. Like with other Ruby & Watir-Webdriver commands, the more you use it, the more you will realize its versatility. Find ways to incorporate index into both your new and old automation scripts!