FotisK
FotisK

Reputation: 1177

How to loop with CasperJS and find all tr id's

I am trying to find a way to fetch one by one some id's and do for each of them some modification:

enter image description here

The above list of id's is not fixed so it can be that i have none or max. 15!

I was starting using repeat, but how I have a problem to fetch the next one (I am fetching always the first one). I assume because I can't use the variable count in the xp:

casper.then(function() {
    var numTimes = 6, count = 0;
    casper.repeat(numTimes, function(count) {
        var name = this.evaluate(function(count) {
        var xp = '//*[contains(@id, "connectedToNeType[' + count + ']")]'
        var element = __utils__.getElementByXPath(xp).getAttribute('id');
            return element;
        });
        this.echo(JSON.stringify(name));
    }, ++count);
});

Each tr id has the below code:

enter image description here

My goal at the end would be to fetch the check box id and select/un-select. This part should be easy as soon i get the correct id name!

BTW, I did also tried to use getElementByXPath searching with text containing the text 'ABC_', because every of those have a title3 with 'ABC_xxx'.

Upvotes: 0

Views: 320

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

Correct indentation would have probably made the problem a little more apparent. casper.repeat() takes two arguments, but not three. The third argument is supposed to be passed into casper.evaluate(), so count is always undefined which means for some reason that the first element is matched.

casper.then(function() {
    var numTimes = 6, 
        count = 0;
    casper.repeat(numTimes, function() {
        var name = this.evaluate(function(count) {
            var xp = '//*[contains(@id, "connectedToNeType[' + count + ']")]'
            var element = __utils__.getElementByXPath(xp).getAttribute('id');
            return element;
        }, ++count);
        this.echo(JSON.stringify(name));
    });
});

Also, you don't need XPath to do that. CSS selectors support attribute selectors:

var name = this.evaluate(function(count) {
    var sel = '[id*="connectedToNeType[' + count + ']"]';
    var element = document.querySelector(sel).id;
    return element;
}, ++count);

Upvotes: 1

Related Questions