Get css parameter without creating element
I selected the following class:
.specialCell {
padding-left: 10px;
}
I would like to use this value as a property in JS like
var specialCellLeftPadding = getCssValue('.specialCell', 'padding-left');
The only way I can think of is to create an element with the desired class and get the desired attribute value:
var tmpElt = document.createElement('div');
tmpElt.className = 'specialCell';
document.body.appendChild(tmpElt);
var specialCellLeftPadding = getComputedProperties(tmpElt).getPropertyValue('padding-left');
document.body.removeChild(tmpElt);
Is it possible to achieve the same goal without creating and adding a new element to the dom? (if no element with this class exists).
+3
source to share
2 answers
You can query CSS information directly from stylesheets using CSSOM . For example,
var stylesheet = document.styleSheets[0];
document.getElementById('output').innerHTML = stylesheet.cssRules[0].style.paddingLeft;
.test { padding-left: 12px; }
Padding left: <span id="output"></span>
+1
source to share
Borrowing from the example dystroy's answer you can get the css value using the document.styleSheets property
Using css
.specialCell {
padding-left: 10px;
}
and
function getCssProperty(cssclass, property) {
for (var i = 0; i < document.styleSheets.length; i++) {
var styleSheet = document.styleSheets[i];
var cssRules = styleSheet.rules || // chrome, IE
styleSheet.cssRules; // firefox
for (var ir = cssRules.length; ir-- > 0;) {
var rule = cssRules[ir];
if (rule.selectorText == "." + cssclass) {
return rule.style.getPropertyValue(property);
}
}
}
}
var prop = getCssProperty('specialCell', 'padding-left');
console.info(prop);
this example will print 10px
to console
+1
source to share