Search code examples
javascriptpythondomrectangles

Find the element with the largest area (main content area)?


Given a web page, how do you find the largest rectangle on the webpage which is the main content area?

For example, compare the size of sidebar, header, footer, and main content area. Is it possible to find the main content area by simply searching for the largest rectangle out of all the rectangles discovered on a page?

Usually the tallest and widest rectangle is suspected to be the main content area, wondering if there's an algorithm of some sort in Javascript or Python to test this hypothesis out.


Solution

  • The current answer is overly complex. The main thing you need to know is element.getBoundingClientRect();. Here's a smaller function - I'm looking for the biggest table but you can use any CSS selector you want.

    // Fix NodeList.sort()
    NodeList.prototype.sort = Array.prototype.sort
    
    var elements = document.querySelectorAll('table')
    
    var getArea = function(element){
        var rectangle = element.getBoundingClientRect();
        return rectangle.width * rectangle.height;
    }
    
    elements.sort(getArea)[0]