Reputation: 117
I've tried this in IE9 only, and I'm receiving just an empty string back - no border width. What is wrong?!
<!DOCTYPE html><html><head>
<style type="text/css">
.myCanvas {
border-width: 2px;
border-style: solid;
border-color: red;
}
</style>
</head><body>
<div class="myCanvas">Something here</div>
<script type="text/javascript">
(function(){
var borderWidth = document.getElementsByTagName('div')[0].style.borderWidth;
console.log(borderWidth);
})();
</script>
</body>html>
Upvotes: 2
Views: 283
Reputation: 128791
The style
object only contains data stored in the element's HTML style
attribute. Here the element has no style
attribute, let alone a border-width
declaration within. This would only work if your markup looked like this:
<div class="myCanvas" style="border-width:2px">Something here</div>
2px
To pull computed CSS styles, you need to use window.getComputedStyle()
:
var div = document.getElementsByTagName('div')[0],
borderWidth = window.getComputedStyle(div).borderWidth;
console.log(borderWidth);
2px
Unfortunately this will not work on IE8, but will work on all other modern browsers. (Browser Support)
Upvotes: 4
Reputation: 6809
element.style
only refers to the element's style attribute. From MDN:
To get the values of all CSS properties for an element you should use
window.getComputedStyle()
instead.
Upvotes: 1