3

I can easily check what CSS style an element has if it was applied inline:

<p style="color: red;">This is red</p>

The JS to read that color:

document.querySelector('p').style.color == 'red'

How can I check the CSS style of an element if that style was applied from an internal or external stylesheet?

at.
  • 50,922
  • 104
  • 292
  • 461
  • 3
    `window.getComputedStyle` – dfsq Dec 20 '16 at 19:19
  • Why do you want to do this? Trying to do this is normally a code smell. It indicates that you may be trying to use CSS styles as a way to maintain program state, which is generally not a good idea. Judicious use of classes and adding them and removing them can usually make trying to query the current style unnecessary. –  Dec 20 '16 at 19:37

2 Answers2

3

You can use window.getComputedStyle(). The returned value is a CSSStyleDeclaration, and you can access the properties directly using the dot notation or use .getPropertyValue('property name').

var p = document.querySelector('.demo');
var style = window.getComputedStyle(p);

console.log(style);

console.log('style.color ', style.color);

// or

console.log('getPropertyValue(\'color\')', style.getPropertyValue('color'));
.demo {
  color: red; 
}
<p class="demo">This is red</p>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

use jQuery css method to get the value of property for the first matched element. The following code will get the color property for the first p-tag in the document. Use an id on the element to select a specific tag.

var color = $("p").css("color");
timk260
  • 129
  • 5