Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click a link in only a single class

I have elements that can be in one of two state class="icon" or class="icon active".

I thought that $browser.element(:class => /^icon$/).click would click the first button that isn't active but it just clicks the first one it finds regardless of whether or not it also contains "active."

Is the regex wrong? Or better yet, is there a non-regex way of doing it?

like image 870
thisisauserid Avatar asked Mar 24 '23 07:03

thisisauserid


2 Answers

As mentioned in the comments, the regex you used should work in watir-webdriver. However if you need a solution that will work in both watir-classic and watir-webdriver, you will need to use find.

b.elements.find{ |e| e.class_name == 'icon'}.click

This will only matches elements where the 'class' attribute is exactly 'icon'.

It is slower and less readable, but allows you to bypass watir-classic's method for matching classes. As seen below, watir-classic will check that the regex matches any of the element's classes.

def match_class? element, what
  classes = element.class_name.split(/\s+/)
  classes.any? {|clazz| what.matches(clazz)}
end
like image 184
Justin Ko Avatar answered Apr 12 '23 18:04

Justin Ko


This is theoretical, and I apologize for not having the time to construct a fake page and test to see if it works

browser.element(:class => /icon(?!active)$/).click  

This works in theory (the regex) matching a line like icon but not icon active but, there may be some under the hood magic that goes on with how class names are matched which might cause it to return the wrong line.

If that does not work let me know, I'll suggest an alternative approach, which while less elegant, ought to work.

For reference I used the Rubular online regex tester along with this SO answer Regular expression to match a line that doesn't contain a word? to some up with that.

like image 37
Chuck van der Linden Avatar answered Apr 12 '23 17:04

Chuck van der Linden