I am trying to access css property like this:
.box {
position: absolute;
background-color: red;
height: 10px;
width: 10px;
}
JS:
var height = $('.box').css('height');
I know, the above code is wrong and this actually doesn't work as .box is not available in the DOM.
Another thing that i tried:
var height = $("<span class='box'></span>").css('height');
My question is: how can I get the height of .box without having any element in the DOM with class box ?
On a modern browser you could use document.stylesheets, and the stylesheet would need to be in the original HTML and the source needs to match the Same Origin Policy, i.e. you can't inject the stylesheet from say a Chrome extension as it does not show in document.stylesheets
CSS
.box {
position:absolute;
background-color:red;
height:10px;
width:10px;
}
Javascript
function propertyFromStylesheet(selector, attribute) {
var value;
[].some.call(document.styleSheets, function (sheet) {
return [].some.call(sheet.rules, function (rule) {
if (selector === rule.selectorText) {
return [].some.call(rule.style, function (style) {
if (attribute === style) {
value = rule.style.getPropertyValue(attribute);
return true;
}
return false;
});
}
return false;
});
});
return value;
}
console.log(propertyFromStylesheet(".box", "height"));
Output
10px
On jsfiddle
The only way you can get then without using a DOM element is by downloading the stylesheet and parsing the contents. You can also access the compiled stylesheet by going to document.stylesheets and finding the rule. You can also use window.getComputedStyle(element) and create an element such as document.createElement('div') and attach the '.box' className to it.
Keep in mind that doing any of this implies that the stylesheet is on the same domain and port of where your html file is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With