How to iterate through querySelectorAll results in Nightwatch
Asked Answered
T

2

7

I can't seem to find the correct syntax for iterating through the innerHTML of a nodelist in Nightwatch. I'm trying to return the urls of every 'a' tag contained within the body content of a page, but I can't find a way to access the results of my querySelectorAll command in Nightwatch.

browser.execute(function() {
    return document.querySelectorAll("div.field-item.even a");
},
function(tags){
    console.log(tags.value);
    console.log(tags.value[9]);
})

There are 10 links on the page I am testing. The query selector seems to be retrieving them all, since console.log(tags.value) prints the following:

[ { ELEMENT: '1' },
  { ELEMENT: '2' },
  { ELEMENT: '3' },
  { ELEMENT: '4' },
  { ELEMENT: '5' },
  { ELEMENT: '6' },
  { ELEMENT: '7' },
  { ELEMENT: '8' },
  { ELEMENT: '9' },
  { ELEMENT: '10' } ]

and console.log(tags.value[9]) prints:

  { ELEMENT: '10' }

I cannot find a way to retrieve the link from these results, however. Appending .innerHTML to any of these variables returns 'undefined'. Is there any way for me to iterate through the querySelectorAll results and retrieve the urls inside of it?

EDIT: It seems like I can get the same result if I use the following code:

browser.elements("css selector", "div.field-item.even a", function(tags) {
    console.log(tags.value);
    console.log(tags.value[9]);
})

I originally thought that I was working with a nodelist, but I think I'm actually being returned a WebElement JSON object as per the documentation for the .elements command.

I'm still unable to access the inner text, however. Any ideas?

Teredo answered 10/11, 2015 at 15:19 Comment(1)
Possible duplicate of How to loop through selected elements with document.querySelectorAllElectrophorus
T
7

I resolved the issue using a different method. I used the browser.elements command instead of querySelectorAll, and then used browser.elementIdAttribute to get the contents of each 'href' attribute in each 'a' tag.

  //Get an WebElement JSON object array of all urls
  browser.elements("css selector", "div.field-item.even a", function(link_array) {
    for (var x = 0; x < link_array.value.length; x++){
      //Fetch the url from each 'a' tag in the content
      browser.elementIdAttribute(link_array.value[x].ELEMENT, "href", function(links) {
        console.log(links.value);
      });
    }
  })

This prints out every link within the content of the page.

Teredo answered 10/11, 2015 at 17:3 Comment(0)
D
0
selectAllRoles: function (client) {
        client.elements('css selector', '.editorDetail ul li input[type=checkbox]', function(res) {
            res.value.forEach(elementObject => {
                client.elementIdClick(elementObject.ELEMENT);

            });
        });

        return this;
    },

Fill in your id's after the 'css selector'

Doan answered 12/7, 2017 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.