Get a CSS value from external style sheet with Javascript/jQuery

css, javascript, jquery

Solution

With jQuery:

// Scoping function just to avoid creating a global
(function() {
    var $p = $("<p></p>").hide().appendTo("body");
    console.log($p.css("color"));
    $p.remove();
})();
p {color: blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Using the DOM directly:

// Scoping function just to avoid creating a global
(function() {
    var p = document.createElement('p');
    document.body.appendChild(p);
    console.log(getComputedStyle(p).color);
    document.body.removeChild(p);
})();
p {color: blue}

Note: In both cases, if you're loading external style sheets, you'll want to wait for them to load in order to see their effect on the element. Neither jQuery's `ready` nor the DOM's `DOMContentLoaded` event does that, you'd have to ensure it by watching for them to load.

Problem

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?

Original source

Related problems