Robert Choy
Robert Choy

Reputation: 105

Click on some element based on its text content in CasperJS

I have the following retrieved from the web page:

<a href="#" onclick="onClkRdMsg(this, 'IPM.Note', 1, b4);">next page</a>

the onclick=onClkRdMsg is constantly changing, is there any method to click on the next page button directly?

since the onclick selector is keep changing, and the href=# if not working, sorry for not having code included here.

just want to know how to click on the next page...

casper.then(function (){
    this.click("[????='next page']");
});

what is the ????

Upvotes: 2

Views: 1849

Answers (2)

Artjom B.
Artjom B.

Reputation: 61902

casper.click("[????='next page']"); invokes a click using a CSS selector. CSS selectors are not capable of matching an element based on its content (text).

It's easy with XPath expressions, though:

var x = require('casper').selectXPath;
...
casper.click(x('//*[contains(text(),"next page")]'));

If you're sure that there is no whitespace around the search text, then you can also use casper.clickLabel():

casper.clickLabel('next page');

Upvotes: 3

Vaviloff
Vaviloff

Reputation: 16838

You have to check every link on the page for text "next page":

casper.evaluate(function(){
    var tags = document.getElementsByTagName("a");
    var searchText = "next page";
    var found;

    for (var i = 0; i < tags.length; i++) {
      if (tags[i].textContent == searchText) {
        found = tags[i];
        found.click();
        break;
      }
    }
})

Based on How to get element by innerText

Upvotes: 0

Related Questions