I would like to write JavaScript code that "aligns" the DOM of an arbitrary web page while maintaining a visual appearance (but not necessarily resizing or other dynamic behavior).
In theory, I believe that this is just a matter of recording the position of each element relative to the window (ex PPKfindPos(element) ) as well as the computed CSS (ex window.getComputedStyle(element).cssText) styles , moving the element from it parent to the direct child element of the "body", which makes it absolutely positioned in the previously recorded position and sets the recorded CSS attributes directly to the element.
I have had some success with this approach, but it is not close to perfection:
function walkDOM(element, parent, nodes) {
parent = parent || { top : 0, left : 0, depth : 0 };
nodes = nodes || [];
if (element.nodeType === 1) {
var node = findPos(element);
node.element = element;
node.width = element.scrollWidth;
node.height = element.scrollHeight;
node.depth = parent.depth + 1;
node.cssText = window.getComputedStyle(element).cssText;
nodes.push(node);
for (var i = 0; i < element.childNodes.length; i++) {
walkDOM(element.childNodes[i], node, nodes);
}
}
return nodes;
}
function findPos(element) {
var position = { left : 0, top : 0 };
if (element.offsetParent) {
do {
position.left += element.offsetLeft;
position.top += element.offsetTop;
} while (element = element.offsetParent);
}
return position;
}
var nodes = walkDOM(document.body);
nodes.forEach(function(node) {
var e = node.element;
if (e !== document.body)
e.parentNode.removeChild(e);
e.style.position = "absolute";
e.style.top = node.top + "px";
e.style.left = node.left + "px";
e.style.width = node.width + "px";
e.style.height = node.height + "px";
e.style.zIndex = node.depth + 1;
if (e !== document.body)
document.body.appendChild(e);
});