How to click on a div in Nightwatch.js

Marika Lam
2 min readSep 28, 2022

There are many ways to wait then click on a div in Nightwatch.js, however I face the issue of the button not being consistently clicked every time.

Here is a solution I found that will not fail you.

browser.execute(function(selector) {
document.querySelector(selector).click();
}, ['YOURSELECTOR'])

Here is another option of waiting and clicking for an element. However, with some div elements, I have faced issues of the element not being clicked.

'Keyword Events or Key Press': function (browser) {
browser
.url('https://the-internet.herokuapp.com/key_presses')
.waitForElementVisible('#target')
.click('#target')
.keys('J')
.assert.containsText('#result', 'You entered: J')
.keys(browser.Keys.BACK_SPACE)
.assert.containsText('#result', 'You entered: BACK_SPACE')
}

.url(‘https://the-internet.herokuapp.com/key_presses’) — Opens the URL in the browser.

.waitForElementVisible(‘#target’) — Wait for the input box to be visible on the web page.

.click(‘#target’) — Clicks inside the input box.

keys(‘J’).keys() is an API method to send key strokes to current element. Here we are sending the alphabet ‘J’.

.assert.containsText(‘#result’, ‘You entered: J’) — Asserting the text ‘You entered: J’ on the web page.

--

--