user123123123 user123123123 - 2 years ago 80
CSS Question

JavaScript - 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 i mean "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 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 */

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

/* MUST RETURN => blue */

Answer Source

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'); = 'none';

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)"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download