Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a css parameter without creating an element [duplicate]

Tags:

javascript

css

I dispose of the following class :

.specialCell {
  padding-left: 10px;
}

I would like to use this value as a property in JS, eg

var specialCellLeftPadding = getCssValue('.specialCell', 'padding-left');

The only way I can think of would be to create an element with the wanted class and get the seeked 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 purpose without creating and adding an new element to the dom ? (assuming no element with this class exists).

like image 301
merours Avatar asked Aug 23 '26 00:08

merours


1 Answers

You can query CSS information directly from stylesheets using the CSSOM. E.g.,

var stylesheet = document.styleSheets[0];

document.getElementById('output').innerHTML = stylesheet.cssRules[0].style.paddingLeft;
.test { padding-left: 12px; }
Padding left: <span id="output"></span>
like image 132
André Dion Avatar answered Aug 24 '26 14:08

André Dion