carloseduleal
carloseduleal

Reputation: 49

How to get element text/value/innertext using Nightwatch?

I have 10 elements with the same class ('botaoParametroAc') and I would like to check one by one and use a click on element that contains "id" as text. This is my code right now:

browser
    .waitForElementVisible('#txtBusca', 4000)
    .elements('class name', 'botaoParametroAc', function(res) {
      for(var item in res.value){
        console.log(item.text)
      }
    });

It is returning "undefined" for each item.

When I try to print res.value, it is the result:

{"ELEMENT":"0.06577812833436414-2"} {"ELEMENT":"0.06577812833436414-3"} {"ELEMENT":"0.06577812833436414-4"} {"ELEMENT":"0.06577812833436414-5"} {"ELEMENT":"0.06577812833436414-6"} {"ELEMENT":"0.06577812833436414-7"} {"ELEMENT":"0.06577812833436414-8"} {"ELEMENT":"0.06577812833436414-9"} {"ELEMENT":"0.06577812833436414-10"}

How can I get the text or attributes of each element?!

Upvotes: 2

Views: 4905

Answers (3)

jason
jason

Reputation: 5

As of the current nightwatch version (1.7.6) it seems like the simplest way to do this in a way that is compatible with both Chromedriver and Geckodriver is with getElementProperty:

browser.getElementProperty('#thisElementId .some-class-name', 'innerText', 
  function(result) {
    console.log('result', result);
  }
);

Upvotes: 0

Brimstedt
Brimstedt

Reputation: 3140

For me, using elements + elementIdAttribute wasn't working well.

What I did instead was use execute():

'Verify table summary': function (browser) {
    browser.execute(function (data) {
      var innerTotal = 0;
      document.querySelectorAll('.cell-with-number')
         .forEach(a => innerTotal += Number(a.innerText));
      return innerTotal;
    }, [], function(res) {
      total = res.value;
    });

The var total will have the value returned from the script run in the contex of the browser.

Upvotes: 0

carloseduleal
carloseduleal

Reputation: 49

Just to update, it is working right now. I needed to get the elementIdAttribute for each element getting innerText to discover it and click on it when condition matches.

        browser
        .waitForElementVisible('#txtBusca', 4000)
        .elements('class name', 'botaoParametroAc', function(result) {
            result.value.map(function(element, err) {
                browser.elementIdAttribute(element.ELEMENT, 'innerText', function(res) {
                    if (res.value == 'id') {
                        browser.elementIdClick(element.ELEMENT);
                    }
                })
            })
        })

Upvotes: 1

Related Questions