Skip to content

How to get the value of a CSS property in JavaScript

New Course Coming Soon:

Get Really Good at Git

Say you want to fetch the value of a CSS property in a web page, one that is set using a stylesheet. How can you do so?

Say you want to fetch the value of a CSS property in a web page, one that is set using a stylesheet.

The style property of an element does not return it, because it only lists CSS properties defined in inline styles, or dynamically.

Not the properties defined in an external stylesheet.

So, how do you do it? Use getComputedStyle(), a global function:

const element = document.querySelector('.my-element')
const style = getComputedStyle(element)
style.backgroundColor //the RGB value
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: