Store multiple DOM elements in an array using CasperJS

For the past two hours, I have been trying to query for DOM elements and store them in an array using CasperJS, so after that I can skip them and fire the click event.

Say my markup looks like this:

<ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> 

Now I want to save each <li> Array, then loop, fire the Click event, and then take a capture.

This is one of the things I tried:

 var listItems = []; casper.start(); casper.open(urlHere, function () { listItems.push(this.evaluate(function () { return document.querySelectorAll('ul > li'); })); this.echo(listItems); }); 

It returns [ , , , ] ,,, [ , , , ] , which basically means that they are all null .

Can someone direct me in the right direction?

Thanks!

+4
source share
2 answers

Try the following:

 var listItems = []; casper.start(urlHere, function () { listItems = this.evaluate(function () { var nodes = document.querySelectorAll('ul > li'); return [].map.call(nodes, function(node) { return node.textContent; }); }); this.echo(listItems); }); 

Basically, you cannot return values โ€‹โ€‹that cannot be serialized from this.evaluate() , but rather are well explained in the docs.

+10
source

I don't know anything about CasperJS, but the array is considered an object in JavaScript, so the array will have an object type. Have you tried scrolling it with a for loop?

 var i; for(i=0;i<listItems.length;i++) { var item = listItems[i]; } 

Alternatively, if you have an actual object containing the objects of your list object, you can do the following:

 for(i in listItems) { if(listItems.hasOwnProperty(i)) { var item = listItems[i]; } } 

Edit: this is just checking that you really have a valid array containing your elements.

+1
source

All Articles