CSS
In CSS you can use a selector. They allow you to choose the elements of marriage; or those that are on the same nesting level and with the same parent element. There are two types of selectors:
- '+' adjacent sibling selector
- '~' general sibling selector (adjacent or non-adjacent siblings)
It is usually ideal to avoid overlapping text whenever possible. (This makes writing your specifications easier and also means that text changes are less likely to violate your specifications.) In this ideal world, your βh3β elements can have identifiers on them, and we could simply:
find('h3#name2+table')
However, in your example, they do not have identifiers, so letβs connect a couple of requests to the scope for what we want.
find('h3', text: 'Name2').find('+table')
First, we found the correct element "h3" (using text matching), and then with this query, as a basis, we request the element "table" sibling.
You may also notice that if you used the general "~" selector, you would get an ambiguous element error; Capybara found all the elements of the table, not just the neighboring ones.
XPath
Sometimes XPath is actually easier to use if you are really forced to select text elements. So you could instead:
find(:xpath, "//h3[contains(text(),'Name2')]/following-sibling::table")
Itβs harder to read, but it does the same. First find "h3" with the text "Name2" and then select the sibling element "table".
source share