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>
How modify a property of external CSS file using jQuery / Javascript
I create a js method to achieve this:
function getStyleSheet(cssName, rule) {
for (i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href.toString().indexOf(cssName) != -1)
for (x = 0; x < document.styleSheets[i].rules.length; x++) {
if (document.styleSheets[i].rules[x].selectorText.toString().indexOf(rule) != -1)
return document.styleSheets[i].rules[x];
}
}
return null;
}
To change any property only is required the following:
getStyleSheet('star-rating', '.rating-container .rating-stars').style.color = "#AFAFAF";
Access CSS file contents via JavaScript
you could load the content with a simple ajax get
call, if stylesheet is included from the same domain
Edit after your update:
I tried this code (on FX10) as a proof of concept that uses only one request to the CSS but it seems a bit hacky to me and should be tested and verified. it also should be improved with some fallback if javascript is not available.
CSS (external file test.css)
div { border: 3px solid red;}
HTML/jQuery
<!doctype html >
<html>
<head>
<!-- provide a fallback if js not available -->
<noscript>
<link rel="stylesheet" href="test.css" />
</noscript>
</head>
<body>
<div></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script>
$(document).ready(function() {
$.when($.get("test.css"))
.done(function(response) {
$('<style />').text(response).appendTo($('head'));
$('div').html(response);
});
})
</script>
</body>
</html>
You should see the CSS code inside the div with a red border all around :)
Enjoy.
Read Style properties from external style sheet (from file)
You can load it using the onload
handler. This will be called when the stylesheet has completed loading. Continue from inside the handler.
(It's important to define the load handler before adding the link element to head as when added the load process will start).
Example
I extracted attributes to make it more readable, modify as needed -
(Remember to also handle errors, ie. onerror
).
$("head").append( $("<link rel='stylesheet' type='text/css'>") .attr("href", "http://cdn.sstatic.net/stackoverflow/all.css") .on("load", cssLoaded));
function cssLoaded(e) { alert("wee..."); // the sheet has loaded, continue from here};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jQuery - How to get all styles/css (defined within internal/external document) with HTML of an element
outerHTML (not sure, you need it — just in case)
Limitations: CSSOM is used and stylesheets should be from the same origin.
function getElementChildrenAndStyles(selector) {
var html = $(selector).outerHTML();
selector = selector.split(",").map(function(subselector){
return subselector + "," + subselector + " *";
}).join(",");
elts = $(selector);
var rulesUsed = [];
// main part: walking through all declared style rules
// and checking, whether it is applied to some element
sheets = document.styleSheets;
for(var c = 0; c < sheets.length; c++) {
var rules = sheets[c].rules || sheets[c].cssRules;
for(var r = 0; r < rules.length; r++) {
var selectorText = rules[r].selectorText;
var matchedElts = $(selectorText);
for (var i = 0; i < elts.length; i++) {
if (matchedElts.index(elts[i]) != -1) {
rulesUsed.push(rules[r]); break;
}
}
}
}
var style = rulesUsed.map(function(cssRule){
if (cssRule.style) {
var cssText = cssRule.style.cssText.toLowerCase();
} else {
var cssText = cssRule.cssText;
}
// some beautifying of css
return cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}");
// set indent for css here ^
}).join("\n");
return "<style>\n" + style + "\n</style>\n\n" + html;
}
usage:
getElementChildrenAndStyles("#divId");
Can jQuery get all CSS styles associated with an element?
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
Related Topics
Get a CSS Value With JavaScript
How to Change the Style of Alert Box
Angular: Conditional Class With *Ngclass
Jquery Svg, Why Can't I Addclass
How to Hide a ≪Option≫ in a ≪Select≫ Menu With Css
Can You Control Gif Animation With JavaScript
Ios 8 Removed "Minimal-Ui" Viewport Property, Are There Other "Soft Fullscreen" Solutions
Add/Remove Class With Jquery Based on Vertical Scroll
Set Webkit Keyframes Values Using JavaScript Variable
How to Generate a Simple Popup Using Jquery
Css Transition Doesn't Start/Callback Isn't Called
How to Know If a Font (@Font-Face) Has Already Been Loaded
Get Element CSS Property (Width/Height) Value as It Was Set (In Percent/Em/Px/Etc)
React Js Conditionally Applying Class Attributes
How to Set Font Size Based on Container Size
What Are the Rules For JavaScript'S Automatic Semicolon Insertion (Asi)