Lampy14 Lampy14 - 6 months ago 218
Javascript Question

Can I select an element by its array position in nightwatch.js?

I am looking to automate some of my testing processes and I am relatively new to Nightwatch.js and javascript. Is there a way that I can click an element based on it's class and position in the subsequent array that will be returned if there are multiple elements with the same class.

For example take the following HTML: -

<div class="clickable-button"><p>Some Text</p></div>
<div class="clickable-button"><p>Some Text 2</p></div>
<div class="clickable-button"><p>Some Text 3</P></div>


If I use chrome development tools and run the following command in the console: -

$('.clickable-button')


It returns an array of the three elements listed above.

I would like to click the first
<div>
element and want to know if there is a way I can do this using a CSS selector? I cannot select via the text that appears within the
<p>
tag as this is dynamic data.

I have tried the following commands in Nightwatch: -

browser.click('.clickable-button'[0])

browser.click('clickable-button[0]')


Neither of these options work. Any help or advice would be appreciated.

Answer

You could probably use :nth-of-type

browser.click('.clickable-button:nth-of-type(1)');

BTW :nth-of-type is part of CSS3 so it is not supported by older browsers.