Get CSS by JavaScript

3

Is there any way to get the list of all CSS applied to an element by JavaScript ?

Example:

Let's say I have the following HTML element:

<div id="mega">Content</div>

I also have CSS :

#mega {
  width: 300px;
  height: 200px;
  background-color: lightblue;
}

If I wanted to make a decision based on CSS that is in the element with id="mega" to change or not, you can get that CSS list that was applied to the element by JavaScript ?

    
asked by anonymous 03.11.2017 / 13:05

2 answers

2

You can use window.getComputedStyle(el) , this will give something similar to an object where you can read its properties to know which styles are applied. It is very large because it refers to all properties, but you have the information you are looking for ...

You can use this:

var backgroundColor = window.getComputedStyle(el).backgroundColor;

Example:

var p = document.querySelector('p');
var styles = window.getComputedStyle(p);
console.log('Cor de fundo:', styles.backgroundColor);

// para teres tudo podes fazer assim:
var css = Object.keys(styles).reduce(
  (obj, prop) => (prop.match(/\D/) && (obj[prop] = styles[prop]), obj), {}
);
console.log(css);
p {
  background-color: green;
  padding: 10px;
}
<p style="color: blue;">Teste</p>

This will generate something like this:

{
  "alignContent": "normal",
  "alignItems": "normal",
  "alignSelf": "auto",
  "alignmentBaseline": "auto",
  "all": "",
  "animation": "none 0s ease 0s 1 normal none running",
  "animationDelay": "0s",
  "animationDirection": "normal",
  "animationDuration": "0s",
  "animationFillMode": "none",
  "animationIterationCount": "1",
  "animationName": "none",
  "animationPlayState": "running",
  "animationTimingFunction": "ease",
  "backfaceVisibility": "visible",
  "background": "rgb(0, 128, 0) none repeat scroll 0% 0% / auto padding-box border-box",
  "backgroundAttachment": "scroll",
  "backgroundBlendMode": "normal",
  "backgroundClip": "border-box",
  "backgroundColor": "rgb(0, 128, 0)",
  "backgroundImage": "none",
  "backgroundOrigin": "padding-box",
  "backgroundPosition": "0% 0%",
  "backgroundPositionX": "0%",
  "backgroundPositionY": "0%",
  "backgroundRepeat": "repeat",
  "backgroundRepeatX": "",
  "backgroundRepeatY": "",
  "backgroundSize": "auto",
  "baselineShift": "0px",
  "blockSize": "-20px",
  "border": "0px none rgb(0, 0, 255)",
  "borderBottom": "0px none rgb(0, 0, 255)",
  "borderBottomColor": "rgb(0, 0, 255)",
  "borderBottomLeftRadius": "0px",
  "borderBottomRightRadius": "0px",
  "borderBottomStyle": "none",
  "borderBottomWidth": "0px",
  "borderCollapse": "separate",
  "borderColor": "rgb(0, 0, 255)",
  "borderImage": "none",
  etc...
    
03.11.2017 / 13:54
1

You can use getComputedStyle . Ex:

function ObterCSS(element){
  var css = '';
  var o = getComputedStyle(element);
  for(var i = 0; i < o.length; i++){
    css+=o[i] + ':' + o.getPropertyValue(o[i])+';';
  }
  return css;
}
    
03.11.2017 / 13:25