10

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

sithumc
  • 3,254
  • 8
  • 27
  • 46

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.
  • 41,537
  • 7
  • 86
  • 101
  • 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
5

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,525
  • 11
  • 19
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
  • 462,703
  • 120
  • 1,088
  • 1,195
4

The only way that worked for me was using:

.useXpath()
.click("//*[contains(text(), 'Two')]")
.useCss()      
AndreVitorio
  • 622
  • 1
  • 7
  • 18