How to Retrieve the Value of a CSS Property in JavaScript
If you are looking to obtain the value of a CSS property in a web page that is set using a stylesheet, you may be wondering how to achieve this using JavaScript. The style
property of an element will not suffice since it only returns CSS properties defined inline or dynamically, and not those defined in an external stylesheet.
Thankfully, there is a solution: the getComputedStyle()
function. This global function allows you to retrieve the computed style of an element, including properties defined in stylesheets. Here is an example of how you can use it:
1 | const element = document.querySelector('.my-element'); |
In this example, the querySelector()
function is used to select an element with the class name “my-element”. Then, the getComputedStyle()
function is called with the selected element as its argument, returning an object that represents the computed style of the element. Finally, the desired CSS property, in this case, backgroundColor
, is accessed using dot notation to retrieve its value.
By utilizing the getComputedStyle()
function, you can easily obtain the value of CSS properties set using stylesheets in a web page. This enables you to manipulate and utilize those values dynamically within your JavaScript code.
tags: [“CSS property”, “JavaScript”, “getComputedStyle”]