Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through querySelectorAll results in Nightwatch

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?

like image 400
JoPinsy Avatar asked Nov 10 '15 15:11

JoPinsy


1 Answers

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.

like image 145
JoPinsy Avatar answered Sep 28 '22 01:09

JoPinsy