简体   繁体   中英

Removing a DOM element using CasperJS

Okay basically I have a post:

<div class=post>
  <div class=content></div>
  <div class=content-meta></div>
</div>

thats the prototype of it to help explain

so what I want to do is use some JS to basically delete or hide the div 'content-meta'

Using JQuery I have:

$('.content-meta').remove();

however when I am using CasperJS I am a little puzzled as how I should implement this code.

I am looking to manipulate a post prior to screen capturing it (the screencapture part works fine)

Heres the code (URL's OMITTED) I have been testing with, It picks up the class just fine, but I have no idea where/how to execute the Jquery to remove the detected element prior to screen capture:

casper.start('http://pageurl.com/XYZ', function() {

if (this.exists('.content-meta')) {
    this.echo('found .content-meta', 'INFO');
} else {
    this.echo('.content-meta not found', 'ERROR');
}
this.captureSelector('resultingcapture.png', '.post');
});

casper.run();

TL;DR How do you execute JS/Jquery from within a CasperJS function?

For execute javascript code from CasperJS, You have to use evaluate() method

The evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you're entering the page and execute code as if you were using the browser console.

Your code should be something like this:

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

casper.start('http://pageurl.com/XYZ', function() {

   if (this.exists('.content-meta')) {

       this.echo('found .content-meta', 'INFO');

       //evaluates an expression in the current page DOM context.
       this.evaluate(function(){
          //delete div 'content-meta'
          $('.content-meta').remove();
       });

       this.then(function(){
           this.captureSelector('resultingcapture.png', '.post');
       });

  } else {
      this.echo('.content-meta not found', 'ERROR');
  }
});

casper.run();

Note: This code is going to run only if the webcontext includes jQuery, otherwise you have to remove the div using just javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM