Consider the following (working) PhantomJS piece of code, supposed to click on the first element of class whatever
:
page.evaluate(
function()
{
var a = document.querySelector(".whatever");
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
waitforload = true;
}
);
I'm failing to make it loop on all elements of class whatever
— the problem not being the loop itself of course but the access to querySelectorAll
elements.
I'm stuck here (I replaced the loop by access to first element for easier debugging ; of course there has to be two page.evaluate
calls since the second one would be within the loop) :
var aa = page.evaluate(
function()
{
return document.querySelectorAll(".whatever");
}
)
//for (i=0; i<aa.length; i++)
//{
page.evaluate(
function()
{
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
// aa[i].dispatchEvent(e);
aa[0].dispatchEvent(e);
waitforload = true;
}
);
//}
I tried several variations, removing var
, prefixing variables with document.
, trying to pass aa
as an argument, etc. Nothing worked (I probably missed the right combination, but anyway I'm clearly missing the basis here).
I'm not sure if it has to do with namespaces and scope of variables (I'm very new to JS) or if the issue comes from the querySelectorAll
output (though I checked the size of the array to be correct), since I'm encountering both "ReferenceError: Can't find variable" and "TypeError: 'undefined' is not an object" errors.
Any hint would be welcome.