EN
JavaScript - element border size / width in Vanilla JS
6
points
Quick solution:
var element = document.querySelector('#my-element');
var style = element.currentStyle || window.getComputedStyle(element);
console.log(parseInt(style.borderLeftWidth));
console.log(parseInt(style.borderTopWidth));
console.log(parseInt(style.borderRightWidth));
console.log(parseInt(style.borderBottomWidth));
1. Current style property example
This approach allows to get current style value (even was assigned with selector).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
margin: 0;
height: 140px;
}
div {
border: solid gray;
border-width: 20px 30px 40px 10px; /* [top] [right] [bottom] [left] */
background: cyan;
width: 100px; height: 100px;
}
</style>
</head>
<body>
<div id="my-element">Text...</div>
<script>
var element = document.querySelector('#my-element');
var style = element.currentStyle || window.getComputedStyle(element);
console.log('border-left-width: ' + parseInt(style.borderLeftWidth));
console.log('border-top-width: ' + parseInt(style.borderTopWidth));
console.log('border-right-width: ' + parseInt(style.borderRightWidth));
console.log('border-bottom-width: ' + parseInt(style.borderBottomWidth));
</script>
</body>
</html>
2. Reusable code example
This approach organized above code in reusable function.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
margin: 0;
height: 140px;
}
div {
border: solid gray;
border-width: 20px 30px 40px 10px; /* [top] [right] [bottom] [left] */
background: cyan;
width: 100px; height: 100px;
}
</style>
<script type="text/javascript">
function getBorderWidth(element) {
var style = element.currentStyle || window.getComputedStyle(element);
var result = {
getLeft: function() {
return parseInt(style.borderLeftWidth);
},
getTop: function() {
return parseInt(style.borderTopWidth);
},
getRight: function() {
return parseInt(style.borderRightWidth);
},
getBottom: function() {
return parseInt(style.borderBottomWidth);
}
};
return result;
}
</script>
</head>
<body>
<div id="my-element">Text...</div>
<script>
var element = document.querySelector('#my-element');
var width = getBorderWidth(element);
console.log('border-left-width: ' + width.getLeft());
console.log('border-top-width: ' + width.getTop());
console.log('border-right-width: ' + width.getRight());
console.log('border-bottom-width: ' + width.getBottom());
</script>
</body>
</html>