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:

We want to change the border color of the containing 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.


Div 1
Div 2
Change border color

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:

Div 1
Div 2
Change border color

Full Code:


Div 1
Div 2
Change border color
<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.

Categorized in:

JavaScript,

Last Update: March 20, 2024