Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable inside a selector for querySelectorAll

I'm programming a unit testing script with Nightwatch and I'm attempting to iterate through any 'a' tags contained within several child elements on a page. I'm trying to use querySelectorAll to get the number of 'a' tags within each child, but the statement doesn't seem to work when I introduce an iterating variable to the selector.

The following function is being called within a for loop, with the x variable being passed:

browser.execute(function() {
    return document.querySelectorAll("div.field-item.even *:not(a):nth-child(" + x + ") a").length;
},
    function(links){
        a_total = links.value;
        console.log("a total: " + links.value);
});

The x variable in this context should be 1, but this is what the code returns regardless of what x is equal to:

a total: [object Object]

I'm not sure why it's returning an object when it should be returning a number. It also strangely seems to work if I swap out my x variable for a static number. For example,

return document.querySelectorAll("div.field-item.even *:not(a):nth-child(1) a").length;

gives me the following:

a total: 2

I'm not sure why the selector returns an object. I thought that the selector was just a string. Why doesn't it seem to work when I put a variable into the selector string?

like image 730
JoPinsy Avatar asked Sep 29 '26 14:09

JoPinsy


1 Answers

It looks like the problem was because I did not pass x to the .execute function. I found a GitHub topic on the issue.

The following code seems to work:

browser.execute(function(x) {
    return document.querySelectorAll("div.field-item.even *:not(a):nth-child(" + x + ") a").length;
}, [x],
function(links){
    console.log("a total: " + links.value);
});
like image 136
JoPinsy Avatar answered Oct 02 '26 05:10

JoPinsy