Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically check CSS styles for particular elements? [duplicate]

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?

like image 707
at. Avatar asked Jul 15 '26 09:07

at.


1 Answers

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>
like image 179
Ori Drori Avatar answered Jul 17 '26 22:07

Ori Drori