views:

193

answers:

2

Is it possible to get a value from the external CSS of a page if the element that the style refers to has not been generated yet? (the element is to be generated dynamically).

The jQuery method I've seen is $('element').css('property');, but this relies on element being on the page. Is there a way of finding out what the property is set to within the CSS rather than the computed style of an element?

Will I have to do something ugly like add a hidden copy of the element to my page so that I can access its style attributes?

+1  A: 

Reading the properties of a stylesheet in JavaScript is not something browsers generally support, so yes, your best bet would be to create a hidden element with the appropriate class (or whatever else makes the CSS selector in question apply) and then read the property from that.

Do note that even then you are reading the sum effect of all stylesheets loaded, so if more than one CSS rule applies to your element, you might not get the expected value.

Jakob Kruse
My script lays out a series of `<div>` s in a grid formation, but I need to take into account the width of the border of the elements so that I can add it to the width of the element to get the total width. Maybe I should just have the border style be set when generating the `<div>`s, then I would have access to the border width.
Acorn
+4  A: 

This seems to work:

<style>
p {color: blue}
</style>

$(document).ready(function() {
    var $p = $("<p></p>").hide().appendTo("body");
    alert($p.css("color"));
    $p.remove();
});
karim79
Ah, I see. Is this creating an element with jQuery so that the style attribute can be read from it and then removing it again? Nice idea.
Acorn
Yes, that's exactly what it is.
karim79