Search code examples
javascriptnode.jsnightmare

Nightmarejs, click text, if exists


I use NightmareJS for headless testing.

Sometimes, an element like this appears in the DOM of the site I am browsing.

<div>Error</div>

There is no ID on the div. I need a way to test if a div with the innerText "Error" exists on the current page and if so, click on the div. (There is an eventhandler on it).

My current approach:

.evaluate(()=>{
var elements = Array.from(document.querySelectorAll('div')).filter(div=>/Error/.test(div.innerText));
console.log(elements);
elements[0].click();
})

However, elements is always empty. Any better ideas?


Solution

  • Problem 1: elements array is empty even though the the element is there.

    The filter is not returning any data, you need to use correct filter. How about this in filter instead of that regex?

    div.innerText.includes('Error')
    

    Problem 2: Check if the element exists and if exists then click on it.

    elements[0] && elements[0].click();
    

    Calling an element or any variable like that will return a truthy value && will make sure it calls .click() only if elements[0] returns a truthy value.

    You can clean it up more,

    const element = elements[0];
    !!element && element.click();
    

    Consider there is an element in the page, in that case,

    • !element means, element doesn't exist or !element = false.
    • !!element means, !false, which in turn means, true.

    This will only make sure to run if the final value is true or false.