mingxin zhao
mingxin zhao

Reputation: 109

How to get all the elements' coordinates

If I have know a id of element is "footer" ,I can use

 document.getElementById("footer").getBoundingClientRect();

to get the "footer" element coordinates.

There is all the code

var page = require('webpage').create();

page.open("https://stackoverflow.com/questions/18657615/how-to-render-an-html-element-using-phantomjs", function    (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        window.setTimeout(function () {
            //Heres the actual difference from your code...
            var bb = page.evaluate(function () {
                //return document.body.getBoundingClientRect();
                return document.getElementById("footer").getBoundingClientRect();    
            });

            page.clipRect = {
                top:    bb.top,
                left:   bb.left,
                width:  bb.width,
                height: bb.height
            };
           console.log(bb.top);
           console.log(bb.left);
           console.log(bb.width);
           console.log(bb.height);

            page.render('capture.png');
            phantom.exit();
        }, 200);
    }
});

the result is

4004.6875
0
1075
632.5

I must know the page have element that id is "footer". if there is a unknown webpage, I do not know any info of the webpage. How I can get all the element coordinates.

Maybe traversing the dom can help, but I always get errors. I do not know how to merge the code correctly.

Upvotes: 2

Views: 391

Answers (1)

Artjom B.
Artjom B.

Reputation: 61952

Let's see how we can change the code given in the link you've found:

function theDOMElementWalker(node) {
    if (node.nodeType == 1) {

        //console.log(node.tagName);

        node = node.firstChild;

        while (node) {
            theDOMElementWalker(node);
            node = node.nextSibling;
        }
    }
}

This can be easily extended to "copy" the DOM to a custom representation. For example:

var dom = page.evaluate(function(){
    var root = { children: [] };
    function walk(node, obj) {
        if (node.nodeType == 1) {

            obj.tagName = node.tagName;
            obj.boundingClientRect = node.getBoundingClientRect();

            node = node.firstChild;

            var childObj;
            while (node) {
                childObj = { children: [] };
                obj.children.push(childObj);
                walk(node, childObj);
                node = node.nextSibling;
            }
        }
    }

    walk(document.documentElement, root);

    return root;
});

console.log(JSON.stringify(dom, undefined, 4));

The idea here is to pass in the DOM node and its "simple" representation into the walk function.

Upvotes: 3

Related Questions