There are three ways to solve this problem. Zelko turned to the first, based on the fact that inside the element , for example, in a well-known text. Adam refers to the most common method , which contains or contains an element . I will consider the third method, which is enclosed or next to the element .
If you have a known element that is inside the one you want, you can start by doing this and use the .parent method to get the container element. It can also be used to find the "sibling" element, using .parent to get the one you want through a shared container, such as a table row. The first use is pretty obvious, but the second is probably more common and very useful when working with tables.
For example, let's say you have a table with several rows of data, where one column is the unique part number and the other column has “add to cart” links. Now, if you want to add a specific part to your basket, you can use Index along with the text “add to basket”, using a code similar to this, assuming that it is the 5th link with this specific text
browser.link(:text => 'add to cart', :index => 4).click
But this is fragile, because as soon as the results change (which can happen with live data), your part is not the fifth in this table, and your test will break. You will need confirmation that you have found the correct part, and not something else on this line. However, in any case, you can do something like this:
browser.cell(:text => 'Part no. 123-45').parent.link(:text => 'add to cart').click
In the case of a table cell, the parent element of the cell is usually a row in the table, and thus, in plain English, this means "find the cell with" part No. 123-45 "in it, and then in that find the same row and click on the" Add to the trash. "(although I assume you understood this by simply reading the code.)
You can use this to get any “sibling” or even just “parent”, where there is some unique element near or inside the object that you need to interact with.
You can probably do something similar to Xpath, but luck in any case can be understood by reading the code after five weeks. This is one of the reasons I really prefer Watir and Watir-Webdriver vs Selenium.