user123123123 user123123123 - 6 months ago 8
CSS Question

Can I create an abstract document listened by the CSS engine?

It is possibile to create an abstract copy of my document tree that is also listened by the CSS engine?

What do I mean by "listened by CSS engine?" Simply, when I add an id, class, or attribute, to an element of this abstract document, the CSS selector must change the property values of the element like in the real DOM, and I must be able to access those values by using the

getComputedStyle
method

ex. [CSS]

a {
color: red;
}

.bar {
color: blue;
}


ex. [DOM]

<a href="#">Lorem</html>


ex. [JavaScript]

var copiedDocument = document.copy();
var abstractLink = copiedDocument.getElementsByTagName('a')[0];

/* RETURN => red */
getComputedStyle(abstractLink).getPropertyValue("color");

abstractLink.setAttribute("class", "bar");

/* MUST RETURN => blue */
getComputedStyle(abstractLink).getPropertyValue("color");

Answer

On Firefox, you can just use

var copiedDocument = document.cloneNode(true);

However, on Chrome getComputedStyle only works for elements in the current document tree.

So you can use something like

var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);

var doc = iframe.contentDocument;
doc.replaceChild(document.documentElement.cloneNode(true), doc.documentElement);

var abstractLink = doc.getElementsByTagName('a')[0];
getComputedStyle(abstractLink).getPropertyValue("color"); // "rgb(255, 0, 0)"
abstractLink.className = "bar";
getComputedStyle(abstractLink).getPropertyValue("color"); // "rgb(0, 0, 255)"

document.body.removeChild(iframe);
Comments