Skip to content

How to get the value of a CSS property in JavaScript

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

→ Get my JavaScript Beginner's Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list