3

I'm using casper.evaluate() to get an array of data from within the page. However it seems to fail to return an array (whereas returning strings work flawlessly). What might be the issue?

For clarification: the code in evaluate is:

function(){ 
    return $('#id a').map(function(i, e) { 
        return $(e).attr('href'); 
    }).get(); 
}

The .get() at the end of the call is meant to get an array instead of a jQuery object. BTW, I'm sure jQuery is available in the page.

1
  • btw, my issue wasn't with this part of the code. it works fine inside a .evaluate() call. Commented Feb 20, 2013 at 23:50

3 Answers 3

3

You dont need jQuery here:

casper.evaluate(function() {
    return [].map.call(__utils__.findAll('#id a'), function(node) {
        return node.getAttribute('href');
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

I believe the .get() is unneccesary.

The return without .get() forms a very nice array indeed, have a look at this jsfiddle example http://jsfiddle.net/YFsRw/

r = function(){ 
    return $('#id a').map(function(i, e) { 
        return $(e).attr('href'); 
    }); 
}

var p = r();

// p servers as a nice array :)
for (i = 0; i < p.length; i++) {
    document.write(p[i] + "<br/>");
}

3 Comments

your fiddle actually uses .get(). but although it's Array-like, it's not an array and I don't know how (if) it would come from the page context to casperjs context.
sorry, sth must go wrong, as i tested fiddle with and without .get(), seems the earlier was saved, anyhow, both worked :)
no :( i realized only later it relates to casper. i am sorry for the disrespect of Your time.
0

.toArray() is what you're looking for.

.toArray() [Returns: Array]

Description: Retrieve all the elements contained in the jQuery set, as an array.

function(){ 
    return $('#id a').map(function(i, e) { 
        return $(e).attr('href'); 
    }).toArray(); 
}

Alternatively, there is also $.makeArray(), which works on a broader level, with more than just jQuery element sets, and is called in a static manner.

function(){ 
    return $.makeArray(
        $('#id a').map(function(i, e) { 
            return $(e).attr('href'); 
        })
    ); 
}

(But .toArray() seems more fitting and clearer in this case.)


See this S.O. answer for a comparison of the two.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.