How to Change an Element with CasperJS and Capture a Screenshot
Use CasperJS evaluate() to change page DOM, wait for dynamic content, and capture either an element or the full page.

Direct answer: CasperJS runs your callback inside the page with evaluate() or thenEvaluate(). Change the DOM there, wait until the target exists when content is asynchronous, and then call captureSelector() for the element or capture() for the full page. CasperJS does not expose the remote page’s document directly from the script environment; DOM access and manipulation must happen through Casper#evaluate(). See the CasperJS API reference and FAQ.
Complete working example
This script opens a page, waits for #status, replaces its text in the page context, and captures only that element:
var casper = require('casper').create();
casper.start('https://example.com/');
casper.waitForSelector('#status', function () {
this.evaluate(function () {
var element = document.querySelector('#status');
if (element) {
element.textContent = 'Updated by CasperJS';
}
});
this.captureSelector('status.png', '#status');
});
casper.run();
The example uses documented API calls. Replace the URL, selector, text, and output filename for your page. If the element is rendered synchronously during the initial response, the wait can be omitted. For a full-page image, replace the last line inside the callback with this.capture('page.png').
How CasperJS page context works
A CasperJS program has two distinct environments:

- CasperJS environment: your Node-like automation script, where you call
start(),waitForSelector(),click(), and capture methods. - Page environment: the document loaded by PhantomJS or SlimerJS, where
window,document, CSS selectors, and page JavaScript exist.
evaluate() crosses that boundary. Its callback behaves as though it were executed from the page’s browser console. Values passed into the callback must be serializable, and values returned from it must also cross that serialization boundary. Keep DOM nodes inside the callback rather than attempting to return an element object.
var result = casper.evaluate(function () {
var title = document.querySelector('h1');
return title ? title.textContent : null;
});
casper.echo(result);
The following does not access the remote document correctly because it runs in the CasperJS environment:
// Wrong: document is not the page DOM here.
var element = document.querySelector('#status');
Use thenEvaluate() when you want the mutation to be an explicit queued CasperJS step:
casper.start('https://example.com/');
casper.thenEvaluate(function () {
var badge = document.querySelector('.badge');
if (badge) {
badge.setAttribute('data-state', 'ready');
badge.textContent = 'Ready';
}
});
casper.then(function () {
this.captureSelector('badge.png', '.badge');
});
casper.run();
Changing text, attributes, styles, and classes
Text and HTML
Use textContent for plain text. It avoids interpreting the value as markup. Use innerHTML only when you intentionally want to insert HTML and control the source.
this.evaluate(function (value) {
var node = document.querySelector('#message');
if (node) {
node.textContent = value;
}
}, 'Screenshot ready');
Attributes and form values
this.evaluate(function () {
var image = document.querySelector('#hero');
if (image) {
image.setAttribute('alt', 'Updated hero image');
image.setAttribute('data-captured', 'true');
}
var input = document.querySelector('input[name="email"]');
if (input) {
input.value = 'preview@example.com';
}
});
Styles, classes, and visibility
this.evaluate(function () {
var panel = document.querySelector('.panel');
if (!panel) {
return;
}
panel.classList.add('screenshot-state');
panel.style.backgroundColor = '#111827';
panel.style.color = '#ffffff';
var noisy = document.querySelector('.cookie-banner');
if (noisy) {
noisy.style.display = 'none';
}
});
If the target browser has trouble with classList, modify className instead. Inline styles are useful for a one-off capture; adding a class is easier to maintain when you inject a larger visual state.
Waiting for asynchronous content
Single-page applications often create the target after the initial HTML arrives. waitForSelector() delays the next step until the selector exists, reducing screenshots taken before the page is ready. The documented form accepts a success callback and an optional failure callback.
casper.waitForSelector('#report', function () {
this.echo('Report exists');
}, function () {
this.die('Report did not appear');
});
For content that exists immediately but changes after a request, combine a selector wait with a short explicit delay or a second condition that checks the rendered state:
casper.waitForSelector('#report', function () {
this.wait(500, function () {
this.evaluate(function () {
var report = document.querySelector('#report');
if (report) {
report.setAttribute('data-final', 'true');
}
});
this.capture('report-page.png');
});
});
Do not use a large fixed delay when a selector or state check can express readiness. Fixed sleeps slow every run and still fail when a slow response takes longer than the chosen interval.
Capturing the changed page
Capture the full viewport or page
capture() saves a page screenshot. Pass a filename, and use the page viewport configured for your CasperJS run. A full-page capture is appropriate when the modified element must be shown in its surrounding layout.
casper.then(function () {
this.capture('full-page.png');
});
Capture only one element
captureSelector() finds the region occupied by a selector and writes that region to a target file. It is useful for cards, charts, receipts, and test fixtures where surrounding navigation is irrelevant.
casper.then(function () {
this.captureSelector('invoice.png', '#invoice');
});
Make sure the element has a non-zero layout box. An element hidden with display: none, outside the viewport in a way the runtime cannot render, or not yet inserted can produce an empty or unexpected image. Capture a parent container when a child has no dimensions.
Capture a rectangle
capture() also accepts a clip rectangle. Use it when you need a fixed region rather than a selector’s calculated bounds.
casper.then(function () {
this.capture('header.png', {
top: 0,
left: 0,
width: 1200,
height: 180
});
});
Selector capture follows the element’s rendered bounds, while a clip rectangle follows your fixed coordinates. Choose selector capture for responsive layouts and a clip for a stable, known canvas.
Interactions before the mutation
Use interactions when the desired change represents what a visitor would do. CasperJS documents selector-based click() and keyboard sendKeys(); the latter targets supported input and editable elements.
casper.thenClick('#open-preview');
casper.waitForSelector('#preview', function () {
this.sendKeys('#name', 'Preview user');
this.captureSelector('preview.png', '#preview');
});
Use evaluate() for an explicit DOM mutation such as changing text or an attribute. A click may trigger application logic, analytics, validation, and network requests; direct mutation is deterministic but bypasses those behaviors. Pick the method that matches what the screenshot is meant to represent.
Passing data safely into evaluate
Pass primitive values as arguments instead of concatenating strings into a function body. This avoids quoting mistakes when text contains apostrophes, newlines, or markup.
var label = 'Customer\'s preview';
casper.thenEvaluate(function (newLabel) {
var node = document.querySelector('#label');
if (node) {
node.textContent = newLabel;
}
}, label);
Check for null before using a selector result. A page may vary by account, viewport, consent state, or experiment. If a missing target should fail the job, throw or call die() in the CasperJS step instead of silently capturing an unchanged page.
End-to-end patterns
Fail when the target is missing
casper.start('https://example.com/');
casper.waitForSelector('#status', function () {
var changed = this.evaluate(function () {
var node = document.querySelector('#status');
if (!node) {
return false;
}
node.textContent = 'Updated';
return true;
});
if (!changed) {
this.die('The status element disappeared before mutation');
}
this.captureSelector('status.png', '#status');
}, function () {
this.die('The status element never appeared');
});
casper.run();
Change several elements atomically
casper.thenEvaluate(function () {
var title = document.querySelector('h1');
var price = document.querySelector('.price');
var footer = document.querySelector('footer');
if (title) { title.textContent = 'Preview title'; }
if (price) { price.textContent = '$0.00'; }
if (footer) { footer.style.display = 'none'; }
});
casper.then(function () {
this.capture('composed.png');
});
One page-context callback prevents a capture from occurring between related changes. Keep the callback small and serializable; complex orchestration belongs in CasperJS steps.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
document is not defined or no DOM change |
The selector code ran in the CasperJS environment. | Move all DOM access into evaluate() or thenEvaluate(). |
| Screenshot shows original text | Capture ran before the mutation or before the app finished rendering. | Queue the mutation, wait for the selector, then capture in a later step. |
| Selector wait times out | Wrong selector, route failure, authentication wall, or JavaScript error. | Log the current URL and page text, verify the selector in the loaded page, and inspect the runtime console. |
| Element image is blank or cropped | The element has zero dimensions, is hidden, or its bounds changed. | Capture a visible parent, set required styles, or use a clip rectangle. |
| Changes disappear after a moment | A framework rerender replaced the node. | Mutate after the final render condition, or trigger the application’s own state update through a click or input. |
| Fonts or images are missing | Resources loaded after capture or failed in the legacy runtime. | Wait for a reliable ready selector, add a modest delay, and verify resource URLs and runtime compatibility. |
| Syntax works in a modern browser but not CasperJS | The project uses an older JavaScript engine. | Use syntax supported by your installed PhantomJS or SlimerJS version and avoid unsupported language features. |

Reliability, performance, and maintenance
Keep each run deterministic: set a known viewport, use stable selectors, wait on observable page state, and make mutations idempotent. An idempotent mutation can run twice without producing different output, which helps when a retry occurs. Prefer a data attribute or semantic class over a long positional CSS selector.
Every additional wait, interaction, and resource increases wall-clock time. Block irrelevant requests only when your page does not need them; blocking a stylesheet, font, or API response can change layout and invalidate the screenshot. Reuse a single CasperJS process for a small batch when appropriate, but isolate jobs that require different cookies, user agents, or viewport settings.
CasperJS is a legacy choice. The project repository states that it is no longer actively maintained, and its documentation covers PhantomJS with experimental SlimerJS support. Check the versions of CasperJS and the installed runtime before investigating an environment-specific failure. The repository, documentation landing page, and selectors reference are the primary references.
Or skip the browser setup
If you only need a clean screenshot after changing or presenting a page, ScreenshotNeo provides a single GET request and supports PNG, JPEG, WebP, and PDF output. Its API accepts the same common parameter names used by other screenshot services, which can simplify a migration. Read the ScreenshotNeo API documentation for all options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Each response reports its result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
ScreenshotNeo options for production captures
Beyond a basic URL capture, the API supports full-page screenshots with lazy images loaded, CSS element capture, dark mode, 12 device presets, custom viewports, retina scale, PDF paper sizes and margins, page ranges, HTML/CSS rendering, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector or network-idle waits, request and resource blocking, custom headers, cookies, user agents and Authorization, timezone and geolocation, transparent backgrounds, image resizing, selectable cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Every feature is available on every plan; yearly billing gives two months free.
FAQ
Should I use evaluate() or thenEvaluate()?
Both execute JavaScript in the page context. Use evaluate() inside a current step for an immediate read or mutation; use thenEvaluate() when you want the mutation represented as a queued CasperJS step.
Can I return a DOM element from evaluate()?
No. Return serializable values such as strings, numbers, booleans, or plain objects. Read or modify the DOM inside the callback.
When should I capture the selector instead of the page?
Use captureSelector() when the output should contain only one component. Use capture() when context, surrounding layout, or the complete page matters.
Why does a mutation work manually but fail in automation?
The automated runtime may load a different route, viewport, cookie state, or JavaScript bundle. Log the URL and wait for a page-specific readiness condition before changing the element.
Is CasperJS a good choice for a new project?
It is mainly useful for maintaining existing scripts. The project is no longer actively maintained, so evaluate a current browser automation stack for new long-lived systems.


