Reputation: 19993
Can I find an element (of any type) by its content with Capybara?
Ideally I would like to write code like this:
find('Copy from a paragraph') # finds the p element
find('Copy from a link') # finds a element
find('Copy from a button') # finds button element
etc.
Upvotes: 2
Views: 7347
Reputation: 24935
If you know the type of the element, you could write:
find('p', text: 'text in paragraph')
find('a', text: 'text in link')
find('button', text: 'text in button')
Upvotes: 5
Reputation: 451
Found an answer for a very similar question about how to find an element without specifying its type, and it works for me right now. In my case I firstly define a parent selector and then find an element within this selector by text only.
The answer is not final, but it works. All that is necessary on this step is to deal with exact match better than using regexp.
search = find(:css, #{parent_selector}).find(:css, '*', :text => /\A#{element_text}\z/)
Upvotes: 1
Reputation: 431031
I don't believe there is a solution that you like. Consider this HTML:
<div>
<p>
<span>hello</span>
</p>
</div>
All three of these elements "contain" the text hello
. Every containing element (body
, html
, etc.) would match. Perhaps you can help us understand why you want to do this?
Upvotes: 1
Reputation: 611
all might answer this
desired_element = nil
all('p').each do |elem|
if elem.text == 'Copy from a paragraph'
desired_element = elem
end
end
replace 'p' with 'a' or 'input' as needed.
Hope this helps
Upvotes: 1