Reputation: 6152
I am trying to use casperjs to check if the following element exists in the DOM:
<b>Bar</b>
Is there a simple way to do that using selectors and casper.exists
? The casperjs documentation makes it very unclear.
Upvotes: 4
Views: 4129
Reputation: 302
In case you're trying to select a vague or non-specific selector (No class or ID), using CSS Path worked for me, for example:
this.echo(this.getElementAttribute('html body div.main-container div.central-container div.articles-home h4));
In that case will print the title from the article. It works the same way when using it in exists().
Upvotes: 0
Reputation: 1
if you need to check an other elements. Visit and learn how to find out an element by XPath and basisly follow the answer of BoltClock.
For example : check li with class="a-last"
if (casper.exists(x('//li[@class="a-last"]'))) {
console.log("find the element");
}
Upvotes: 0
Reputation: 724422
The basic use of casper.exists()
is to pass it a selector string and it'll return true or false to indicate whether any elements were found to match that selector.
In your case, however, the only practical selector that would find this element is b
, so if you're specifically looking for a b
element containing this text then you'll need to either specify some form of context (e.g. a parent element), or test this element's existence using XPath instead, which lets you test elements by their text content:
var x = require('casper').selectXPath;
if (casper.exists(x('//b[text()="Bar"]'))) {
// <b>Bar</b> exists
}
Upvotes: 7