Reputation: 1177
This issue today is about how to retrieve tr id from a text that was previously found in the tr with CasperJS.
Example - following page code:
In the above page code we have more of those tr's with id's "connectedToNeType[0]}_TR" but with different number from 0..15.
My goal is to search and find via the text "ABC_123" the according id. The first part to find the "ABC_123" i have managed with the below code:
casper.then(function() {
var xpath = '//*[contains(text(), "ABC_123")]';
var found = this.evaluate(function(xp) {
return __utils__.getElementByXPath(xp);
}, xpath);
if (found === null) {
this.echo("-> NOT FOUND");
this.die();
};
this.echo("FOUND");
...
But how can I get from this point and find the according tr id?
Upvotes: 1
Views: 279
Reputation: 61892
CasperJS has the same limitations that PhantomJS has. The page context is sandboxed and you can only pass primitive objects in and out of it. DOM nodes are not primitive object which is why it is returned as null
. See the documentation:
Note: The arguments and the return value to the
evaluate
function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.Closures, functions, DOM nodes, etc. will not work!
You have to return a representation of element that you're interested in. If you can't do that, then you have to do all the work in the page context.
It seems you want to select the <tr>
element that is the parent of a <td>
element which contains the text that you have. XPath supports matching the parent from a child with ..
. You can simply do this:
casper.then(function() {
var xpath = '//td[contains(text(), "ABC_123")]/..';
var foundId = this.evaluate(function(xp) {
return __utils__.getElementByXPath(xp).id;
}, xpath);
if (foundId == null) {
this.echo("-> NOT FOUND");
this.die();
};
this.echo("FOUND: " + foundId);
});
or with other functions:
var x = require("casper").selectXPath;
...
casper.then(function() {
var xpath = '//td[contains(text(), "ABC_123")]/..';
var foundId = this.getElementAttribute(x(xpath), "id");
if (foundId == null) {
this.echo("-> NOT FOUND");
this.die();
};
this.echo("FOUND: " + foundId);
});
Upvotes: 2