If you want to easily get the computed style of an element without it being rendered on the browser, one simple solution is to hide it by wrapping it in a container with display: none
and adding it to the DOM. This way, you can still access the computed style information.
An example using jQuery demonstrates that when the structure is not connected to the DOM, accessing style information becomes difficult. However, once the structure is appended to the DOM, jQuery can then retrieve the style:
jQuery(function($) {
// Disconnected structure
var x = $("<p style='color: red'><span style='padding: 2em'><span style='background-color: white'>TEXT</span></span></p>");
// Get the span
var y = x.find("span span");
// Show its computed color (will be blank)
display("y.css('color'): " + y.css('color'));
// Create a hidden div, append the structure, and show the computed color (will now display red)
var d = $("<div>");
d.hide();
d.append(x);
d.appendTo(document.body);
display("y.css('color'): " + y.css('color'));
// Detach the div
d.detach();
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
});
View live example | View source code
Note that some properties may not be calculated accurately until the container is visible. If you encounter this issue, make the div
visible but off-page (
position: absolute; left: -10000px
).