Search code examples
webkitphantomjs

Find <p> with biggest font


Say I have different <p> elements in my HTML document. Once rendered and depending on the applied style, some of them might have a bigger font size than the others.

How can I get the content of the <p> which font size is bigger than the rest using PhantomJS? Is that even possible?


Solution

  • Use page.evaluate to evaluates a js function in the context of the web page. To get the font size for a given element, use Window.getComputedStyle.

    Finally, this could be somehting like this

    var page = require('webpage').create();
    var url = 'http://jquery.com/';//just an example
    
    page.open(url, function(status) {
        var results = page.evaluate(function() {
            return [].map.call(window.document.querySelectorAll('p'), function(p) { 
            return {content:p.innerHTML, size:window.getComputedStyle(p)['fontSize']}
            }).sort(function(a, b) {return b.size.replace(/px/, '')-a.size.replace(/px/, '');});
        });
        if(results && results.length>0) {
             console.log(JSON.stringify(results[0]));
        }       
        phantom.exit();
    });