9

Say I have these elements on my web page.

<a href="/dynamic1">One</a> 
<a href="/dynamic2">Two</a> 
<a href="/dynamic3">Three</a>

I want to click on the link with text Two. How to identify or click that element using the Link Text without any unique attributes like id or class.

In .Net I can use driver.findElement(By.linkText("Images")).click();. What is the equivalent in nightwatch.js

sith
  • 1,618
  • 4
  • 23
  • 40

4 Answers4

11

The locator By.linkText uses an XPath internally.

So to click the second link from your example with an XPath :

.useXpath()     // every selector now must be XPath
.click("//a[text()='Two']")
.useCss()      // we're back to CSS now

Note that depending on the inner HTML, you may need to concatenate the children and trim the spaces:

.click("//a[normalize-space()='Some link']")
Florent B.
  • 37,063
  • 6
  • 68
  • 92
  • 1
    This seems surprisingly difficult for something that I assume would be used quite a lot? ... You know - find a link with the text 'ABC' and click it. Or is it just me? – Zeth Jun 23 '19 at 15:45
4

The first param to elements() method is the locator strategy, use link text - it is supported:

client
  .url('http://website.org')
  .waitForElementVisible('body', 1000)
  .elements('link text', 'Two', function (result) {

    for (var i = 0; i < result.value.length; i++) {
      var element = result.value[i];

      // do something
    }
  })
  .end();
alecxe
  • 414,977
  • 106
  • 935
  • 1,083
4

There is a better way now, you can use any of the documented locator strategies. Any one of; id, css selector, link text, partial link text, tag name, xpath.)

browser
  .click('link text', 'Some Link Text');
Ben
  • 1,495
  • 9
  • 19
3

The only way that worked for me was using:

.useXpath()
.click("//*[contains(text(), 'Two')]")
.useCss()      
AndreVitorio
  • 338
  • 4
  • 13