We can use JavaScript to change the border color of a div using the borderColor property.
document.getElementById("div1").style.borderColor = "green";
Let’s say we have the following HTML:
<div id="div1">
<p>We want to change the border color of the containing div.</p>
</div>
If we want to change the border color of #div1 to green, we can use the borderColor property in the following JavaScript code.
document.getElementById("div1").style.borderColor = "green";
The second argument can be any valid css color. So for example, we could use the hexadecimal value for green to change the border color to green.
document.getElementById("div1").style.borderColor = "#00FF00";
Using JavaScript to Change the Border Color of a Div with a Click
To change the border color of a div using JavaScript, we target the borderColor property with a click event.
Let’s say we have the following HTML and we want to change the border color of #div1 to green.
<style>#div1, #div2 { width: 300px; height: 100px; border: 3px solid #000; margin-bottom: 20px; padding: 5px; }</style>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="click-me" onclick="clickFunction()">Change border color</div>
We can utilize both the borderColor property of #div1 along with an onclick event to change the border color of #div1.
Below is the Javascript code which will allow the user to be able to update the border color of the div:
function clickFunction() {
var currDiv = document.getElementById("div1");
currDiv.style.borderColor = "green";
}
The final code and output for this example of how to change the border color of our div using JavaScript is below:
Code Output:
Full Code:
<style>#div1, #div2 { width: 300px; height: 100px; border: 3px solid #000; margin-bottom: 20px; padding: 5px; }</style>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="click-me" onclick="clickFunction()">Change border color</div>
<script>
function clickFunction() {
var currDiv = document.getElementById("div1");
currDiv.style.borderColor = "green";
}
</script>
Hopefully this article has been useful for you to understand how to change the border color of an element using JavaScript.
Leave a Reply