javascript - Click on all 'a' elements in paragraph with specific class in CasperJS -
i have following problem. have structure of html code:
<p class="description"> lorem ipsum, bla bla bla <a href="# onclick="somemethod(id)">click</a> </p> <p class="description"> lorem ipsum, bla bla bla </p> <p class="description"> lorem ipsum, bla bla bla <a href="# onclick="somemethod(id)">click</a> </p> now need click via casperjs on every "a" in paragraphs class 'description'.
i try this:
while (selector = document.queryselector('p.description a')) { casper.then(function () { this.click(selector); console.log('click'); }) } but doesn't work.
are there possibilities how this?
you have 2 problems.
- you cannot use
document,casper@ same time, becausedocumentavailable inside of page context (casper.evaluate()),caspernot available in page context. - you need iterate on clickable elements either in page context or outside.
css selectors
if <p> elements have same parent , there no other elements in between, can use css selectors achieve this:
casper.then(function(){ var numberofelements = this.getelementsinfo("p.description").length; for(var = 1; <= numberofelements; i++) { this.click("p:nth-child("+i+") a"); } }); note it's not possible select :nth-child based on class, assumes no <p> elements there without "description" class.
xpath expressions
it's possible make more robust, using xpath expressions, because more expressive.
var x = require("casper").selectxpath; ... casper.then(function(){ var numberofelements = this.getelementsinfo("p.description").length; for(var = 1; <= numberofelements; i++) { this.click(x("(//p[contains(@class,'description')])["+i+"])/a")); } }); where (//p[contains(@class,'description')])["+i+"]) means nodelist (//p[contains(@class,'description')]) of p elements built contain "description" part of "class" attribute. e.g. (nodelist)[3]) selects third element list.
if want iterate inside of page context, need use a click function inside of page context.
Comments
Post a Comment