4

For the last couple of hours I have been trying to query DOM elements and store them in an array with CasperJS, so then after that, I can loop through them and fire a click event.

Let's say, my markup is like this:

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

Now, I want to store each <li> an an Array, then loop through, fire a Click event, 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 they are all null.

Can someone please direct me in the right direction?

Thank you!

peduarte
  • 1,667
  • 3
  • 16
  • 24

2 Answers2

10

Try this:

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 can't return values which are not serializable from this.evaluate(), it's rather well explained in the docs.

Michael St Clair
  • 5,937
  • 10
  • 49
  • 75
NiKo
  • 11,215
  • 6
  • 46
  • 56
1

I don't know anything about CasperJS but an array is considered an object in JavaScript so an array would have a type of Object. Have you tried looping through it using a for loop?

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

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

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

Edit: This is just to check that you actually have a valid array containing your items.

Jon
  • 418
  • 3
  • 8
  • Hey Jon, I tried both options already but all it returns is `null`. This is getting boring now... Thanks anyway – peduarte Apr 30 '13 at 13:34