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

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.

Leave a Comment