Luca F
Luca F

Reputation: 145

How to use watir with children / xpath to click a button?

I want to write a generic code to click on button.

So i get the class from a div. And the child element is the button. I access the child element with xpath.:

button = browser.div(class: /sp-m-cookies-container/).element(xpath: './*')

puts button.innertext # OUTPUT: Submit

button.click

Even though the OUTPUT is correct (it is the innerText from the button, the click has no effect. However, the below code works (where the button it's not generic).

browser.button(:text => 'Submit').click

What am I doing wrong?

In my case the name isn't "submit". It is often different. Only the class is always the same.

Chrome: 79.0.3945.130

Selenium: 3.141.0

Upvotes: 0

Views: 172

Answers (1)

supputuri
supputuri

Reputation: 14135

Change the first line as below.

button = browser.div(class: /sp-m-cookies-container/).button(xpath: './button').wait_until(timeout: 100, &:present?)

element(xpath: './*') is too generic which will return the first element irrespective of whether it's a button.

If you think normal click is working, then you can use the fire_event :onclick to trigger the click event as shown below.

button.fire_event :onclick

Upvotes: 1

Related Questions