0

Here's an example block of css:

p {
  position: relative;
  color: blue;
  font-size: 100%; 
  top: 100px
}

Then if I include a paragraph tag which calls a javascript function upon being clicked:

<p onclick="logStyles(this)">Test</p>

Strangely, only some styles are accessible...

function logStyles(obj) {
    console.log(obj.style.color);
    console.log(obj.style.position);
    console.log(obj.style.fontSize);
};

The element's color value shows up in the console and I am able to change it's value to say "blue" from my javascript. But the second two functions log nothing to the console and those style values are inaccessible.

 red page.html:16
     page.html:17
     page.html:18

Why is this the case? I am running the latest version of Chrome.

The css and javascript files are included through links in the head as so:

 <script src="js_methods.js"></script>
 <link rel="stylesheet" type="text/css" href="stylesheet.css">
Benjamin Gorman
  • 360
  • 1
  • 11
  • 4
    The "style" object on a DOM node only gives the styles that are directly associated with the element, not styles from CSS files. – Pointy Jul 17 '14 at 18:08
  • A dup of [document.body.style.backgroundColor is undefined](http://stackoverflow.com/q/17588801/1169519)? Just for example, there's probably better posts available. – Teemu Jul 17 '14 at 18:08
  • 1
    @Teemu I agree it's a dupe but can't quite remember the appropriate terminology to search for. – TylerH Jul 17 '14 at 18:09

2 Answers2

0

You're talking about the COMPUTED style. That's something different from the inline style.

See: How do I get a computed style?

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • Thanks for pointing that out. I was able to able to access fontSize for example by writing window.getComputedStyle(obj).fontSize – Benjamin Gorman Jul 17 '14 at 18:17
0

By doing it this way you can only get the styles directly associated with the HTMLElement object. What you're looking for are the computed styles:

var styles = window.getComputedStyles(elem);
console.log(styles["color"]);

See mozilla

SVSchmidt
  • 6,269
  • 2
  • 26
  • 37