Samuel Edwin Ward
Samuel Edwin Ward

Reputation: 6675

How do I locate an element that is a grandchild of another element by its text with watir-webdriver?

I have some HTML like this:

<ul id="directory">
    <li><a id="first" href="/first">first</a></li>
    <li><a id="second" href="/second">second</a></li></ul>

I want to locate the link with id "second" based on its text and relationship to the ul with id "directory" and click on it using watir-webdriver.

It seems like should simply be able to say:

browser.ul(:id => 'directory').li.a(:text => 'second')

but this does not exist.

After researching, I thought maybe I should be doing it like this:

browser.ul(:id => 'directory').lis.a(:text => 'second')

but LICollection doesn't even have an a method. I think maybe I should be doing something with each but I have no idea what it would be.

Is there a good way I can identify this element, without resorting to a CSS or XPath selector, using these criteria:

  1. It is an anchor.
  2. It has the text 'second'.
  3. It is the child of an li element, which is the child of a ul element, which has the ID "directory".

Upvotes: 0

Views: 165

Answers (2)

user3487861
user3487861

Reputation: 350

browser.ul(:id => 'directory').a(:id => 'second')

Let me know is the above statement is working or not.

Upvotes: 0

Justin Ko
Justin Ko

Reputation: 46826

You can do:

browser.ul(:id => 'directory').a(:text => 'second')

In Watir-Webdriver, you do not need to specify the li element to get access to the link. As well, assuming a reasonably formed HTML page, any link in the ul element will be in the li element (ie I believe that the only allowed direct children of ul elements is li elements).

Upvotes: 2

Related Questions