using casperjs to click an html element based on its text

user3228249 picture user3228249 · Jan 23, 2014 · Viewed 7.4k times · Source

I have html elements on my page like this which is on a secure page post the form login

 <h4 class="something" id="somethingelse1" style="display: none;">Some Name</h4>
 <h4 class="something" id="somethingelse2" style="display: none;">Some other name</h4>

I want to be able to simulate the click of this element which then will load a new page. Once that new page is loaded, I want to take a snapshot of a div element within it. I have got part of taking a snapshot, but I am unable to find a way to click the element based on its text. Like for example simulating the click of the H4 element above where the text was 'Some other name'

This is what I have so far...

var casper = require('casper').create({

    pageSettings: {
        loadImages:  true,        
        loadPlugins: true          
    } 
});

casper.start('http://localhost/', function() {

    console.log("page loaded");

    this.fill('form#login-form', { 
        username: 'lbguy', 
        password: 'lbguypass'
    }, true);
});

casper.thenOpen('http://localhost/MysecureSite/page1', function() {
        this.echo(this.getTitle());

    var query_xpath = '//*[@innerHtml="Some other name"]';

    require('utils').dump(this.getElementAttribute(query_xpath , 'id'));  

    //casper.start('http://localhost/MysecureSite/page2', function() {
        //  this.captureSelector('pic.png', '#someelement');    
    //});

});

After the page title the console just outputs "Null". I'm not sure if this is the right approach as well. The objective is to simulate a click of the H4 element based on a selected text that I will send in programmatically, and then take a snapshot on page2 after that click action loads page 2 of a div called someelement.

UPDATE

The h4 elements are dynamically added to the page by jquery after the page has loaded.

Thanks

Answer

NiKo picture NiKo · Jan 25, 2014

Try waiting for your h4 to have been actually added to the DOM, then click on it:

casper.waitForSelector("#somethingelse1").thenClick("#somethingelse1");