-1

So I am trying to retrieve a CSS property from the DOM and the only thing being returned is ""...

e.g. if my CSS code is

nav  {
  color: red;
}

and my javascript is

var nav = document.querySelector("nav");
var navColor = nav.style.color;
console.log(navColor);

All that is returned to console is "". I am new to JS.

If I try to manually make a var and find it's property in the console, it also outputs "", until I change the value of the style property, then it successfully returns the properties value - yes I have definitely set a property I am trying to retrieve and I have checked spelling hundreds of times.

Will Cowan
  • 81
  • 8

6 Answers6

4

Check this link: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

const nav = document.querySelector("nav");
const { color: classStyle } = getComputedStyle(nav);
const { color: inlineStyle } = nav.style;


console.log(inlineStyle)
console.log(classStyle)
nav  {
  color: red;
}
<nav>this is nav</nav>
Joe Warner
  • 3,335
  • 1
  • 14
  • 41
1

You will need to use getComputedStyle() for that:

var navColor = getComputedStyle(nav).color;
Bananicorn
  • 78
  • 7
0

You can query the applied css rule by calling getComputedStyle(document.querySelector("nav")).color

lipp
  • 5,586
  • 1
  • 21
  • 32
0

As mentioned in the comments, the style property only returns inline styles, as in:

 <div style="color: red;"></div>

would return...

 "color: red;"

What you're looking for is the window.getComputedStyle function, which can be used to retrieve final style values. Like so:

 // HTML
 <div class="some-element"></div>

 // CSS
 .some-element {
      color: red;
 }

 // JS
 const someElement = document.querySelector('.some-element');
 console.log(window.getComputedStyle(someElement).getPropertyValue('color'));

This should log out red.

EDIT

Per comment, the output would actually be rgb(255, 0, 0), the RGB equivalent of red. As the function name suggests, it's computing styles, not retrieving their actual values. For example, if you styled with CSS a width to be 10%, getComputedStyle would calculate the pixel value of whatever the final width is rendered as. Not the best solution, but JavaScript generally doesn't need to directly interact with raw CSS files -- that should be up to the CSS and (JavaScript-controlled) classes to manage.

EDIT 2

Just an FYI, you can use .getPropertyValue('color') or just .color, I'm unaware of any preference in the dev community.

sheng
  • 1,226
  • 8
  • 17
0

var nav = document.querySelector("nav");
console.log(getComputedStyle(nav).color)
nav  {
  color: red;
}
<nav>Menu</nav>
Sumesh TG
  • 2,557
  • 2
  • 15
  • 29
0

With .style property You can't access elements css styles if the styles is not inline.

You need to use getComputedStyle function.

Usage:

var nav = document.querySelector("nav");
var navColor = getComputedStyle(nav).color;
console.log(navColor);

For more information please refer to this link