How to click a link using link text in nightwatch.js

sith picture sith · Jul 23, 2016 · Viewed 8.7k times · Source

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

Answer

Florent B. picture Florent B. · Jul 23, 2016

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']")