简体   繁体   中英

Get every element with a specific (data-) attribute in CasperJS

I'm trying to test a page using CasperJS. Are there any possibilities to get every element (paragraphs) which contains attribute data-...? After that, I need to compare this attribute with the inner HTML, but I don't know how to do it.

First you need to retrieve the representations of all of the elements you're interested in. This can be done with casper.getElementsInfo(selector) :

var elements = casper.getElementsInfo("p[data-whatever]");

This will give you all <p> elements on the page that have a data-whatever attribute set. If you want to filter that by the values of the data-whatever attributes, then you need to use the attribute selectors according to your needs.

The getElementsInfo() function contains very much useful information, but doesn't contain the actual elements that you want to use. It only contains a representation as an array.

You can iterate over those element representations and run your operations on them. You said you want to "compare this attribute with inner HTML" . This can be done in this way:

elements.forEach(function(element){
    if (element.attributes["data-whatever"] === element.html) {
        casper.echo("data attribute and content are exactly equal");
    } else {
        casper.echo("data attribute and content are different");
    }
});

Keep in mind that you can do this on the elements directly with the normal DOM functions, but then you would have to do this inside of casper.evaluate() , because PhantomJS (which CasperJS is built upon) has two contexts and the page context is sandboxed. Also, you cannot return DOM nodes from the page context .

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