-2

Started learning web dev and stumbled onto something simple I've been breaking my head over the past hour. It's simple code to show the border color of a div element with an alert. It works. But when I move the style from inline to a style element, it returns nothing.

Working code:

function myFunction() {
  alert(document.getElementById("myDiv").style.borderColor);
}
<div id="myDiv" style="border:thick solid green">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

non-working code:

function myFunction() {
  alert(document.getElementById("myDiv").style.borderColor);
}
<style>
  #myDiv {
    border: thick solid green;
  }
</style>
<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

Only thing I changed is move the style attribute from the div tag to the head. Why did it stop working and how do I fix it?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Possible duplicate of [*How to get all the applied styles of an element by just giving its id?*](http://stackoverflow.com/questions/9430659/how-to-get-all-the-applied-styles-of-an-element-by-just-giving-its-id) – T.J. Crowder Oct 09 '16 at 14:11

2 Answers2

1

The style attribute only gives you inline styles. To get the computed style, you use getComputedStyle (a global function) on standards-based browsers or currentStyle (an element property) on old IE:

function myFunction() {
  var div = document.getElementById("myDiv");
  var style = window.getComputedStyle ? getComputedStyle(div) : div.currentStyle;
  alert(style.borderColor);
}
<style>
  #myDiv {
    border: thick solid green;
  }
</style>
<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

With element.style you read the style attribute of the element. In the second example you removed that attribute, that's the reason it stopped working.

To get the actual styles applied to an element you need to use Window.getComputedStyle(). An example of use of this:

var elem = document.getElementById("myDiv");
var styles = window.getComputedStyle(elem);
alert(styles.borderColor);
germanfr
  • 547
  • 5
  • 19