Search code examples
javascriptautomated-testsnightwatch.jsgetelementsbytagname

Issue with getting an element with dynamic ID with the function getElementsByTagName - NightwatchJS


I am trying to make an automated test using NoghtwatchJS.

I am dealing with a UI that contains elements with dynamic IDs. I have to click on a particular element. I am thinking about using gelElementByTagName('aria-label') in mycase. This is the code I used :

var labels,i
labels = getElementsByTagName('aria-label');
    for ( i = 0; i < labels.length; i++) {
        if (labels[i].htmlFor == 'Next') {
            var elem = getElementById(labels[i].htmlFor)
        };
    };

I have the issue element not defined :

ReferenceError: getElementsByTagName is not defined

Do you have any idea how I could solve this problem?

I have tried :

getElementsByTagName('aria-label')
element.getElementsByTagName('aria-label')
document.getElementsByTagName('aria-label')

Solution

  • The only way to make this work in Nightwatch is to use the execute comand

    Your code should looke something like this:

    browser.execute(function() {
                return document.getElementsByTagName('aria-label').length;
    
            }, function(result) {
                for (let i = 0; i < result.value; i++) {
                    if (labels[i].htmlFor == 'Next') {
                       let elem = getElementById(labels[i].htmlFor)
          };
      });