Javier Sega
Javier Sega

Reputation: 93

Get dynamic id value in CasperJS

I need to get the value of the id = "1" which is dynamic and is immediately after id = "divContenedor".

<html debug="true">
<head>
<script src="chrome-extension://bmagokdooijbeehmkpknfglimnifench/googleChrome.js"/>
<body onload="/*xajax.$('cargando').style.top=document.body.scrollTop+300+'px'; xajax.$('cargando').style.left=document.body.scrollWidth/2-121+'px';*/" onclose="alert('lalala');" style="cursor: default;">
<div id="general" style="text-align: left;">
<table width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 8px;">
<div id="notas" class="notas"/>
<div id="divContenedor" class="central">
**<div id="1">**
<div style="padding: 4px 0px; border-top-width: 1px; border-top-style: solid; border-top-color: rgb(181, 209, 221);">
<div class="menuContenedor">
<span style="float: right;">

My CasperJS code:

var casper = require('casper').create();
casper.start('http:\\www.example.es');

casper.then(function() {
  var id = document.getElementById('divContenedor').firstChild
  this.echo(id);
});

casper.run();

Upvotes: 2

Views: 1527

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

CasperJS is built on top of PhantomJS and use its model of the two contexts. Only the page context is able to access the DOM and you can only pass serializable values in and out of it. This is done through casper.evaluate():

casper.then(function() {
    var id = this.evaluate(function(sel) {
      return document.getElementById(sel).children[0].id;
    }, 'divContenedor');
    this.echo(id);
});

The PhantomJS documentation for evaluate() has an important note:

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!


Other small things:

  • element.firstChild works on nodes an not just elements. So the first child is probably always a TextNode which doesn't have an id.
  • http:\\www.example.es is not a valid URL. Use forward slashes: http://www.example.es/

Upvotes: 2

Related Questions