Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to set the width of an element's border with JavaScript?
To set the width of an element's border in JavaScript, use the borderWidth property. This property allows you to dynamically modify border thickness after the page loads.
Syntax
element.style.borderWidth = "value";
The value can be specified in pixels (px), keywords (thin, medium, thick), or other CSS units.
Example: Changing Border Width
<!DOCTYPE html>
<html>
<head>
<style>
#box {
border: thick solid gray;
width: 300px;
height: 200px;
padding: 20px;
margin: 10px;
}
</style>
</head>
<body>
<div id="box">Demo Text</div>
<br>
<button type="button" onclick="changeThin()">Thin Border</button>
<button type="button" onclick="changeThick()">Thick Border</button>
<button type="button" onclick="changePixels()">5px Border</button>
<script>
function changeThin() {
document.getElementById("box").style.borderWidth = "thin";
}
function changeThick() {
document.getElementById("box").style.borderWidth = "thick";
}
function changePixels() {
document.getElementById("box").style.borderWidth = "5px";
}
</script>
</body>
</html>
Setting Individual Border Sides
You can also set width for individual borders using specific properties:
<!DOCTYPE html>
<html>
<head>
<style>
#multiBox {
border: 2px solid blue;
width: 250px;
height: 150px;
padding: 15px;
margin: 10px;
}
</style>
</head>
<body>
<div id="multiBox">Individual Border Example</div>
<br>
<button type="button" onclick="setIndividual()">Set Individual Borders</button>
<script>
function setIndividual() {
var element = document.getElementById("multiBox");
element.style.borderTopWidth = "10px";
element.style.borderRightWidth = "5px";
element.style.borderBottomWidth = "3px";
element.style.borderLeftWidth = "8px";
}
</script>
</body>
</html>
Border Width Values
| Value Type | Example | Description |
|---|---|---|
| Keywords | thin, medium, thick | Predefined thickness levels |
| Pixels | 5px, 10px, 20px | Exact pixel measurements |
| Other Units | 1em, 2rem, 1% | Relative measurements |
Conclusion
Use the borderWidth property to dynamically change border thickness in JavaScript. You can set all borders at once or control individual sides for precise styling control.
Advertisements
