How to Get Current Value of a CSS Property in JavaScript?



The getComputedStyle() method gives an object which includes all the styles applied to the target element.

Example

The following examples illustrate how we can get and set CSS variables using JavaScript.

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: 4%;
   padding: 4%;
   width: 50%;
   text-align: center;
   background-color: powderblue;
   border-radius: 4%;
}
</style>
</head>
<body>
<div>Test Div</div>
<span></span>
<script>
let element = document.querySelector('div');
let getStyle = window.getComputedStyle(element);
document.querySelector('span').textContent = ('background-color: ' + getStyle.getPropertyValue('background-color') + '.');
</script>
</body>
</html>

Output

This will produce the following result −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   display: flex;
   margin: 4%;
   padding: 4%;
   width: 20vh;
   height: 20vh;
   box-shadow: inset 0 0 23px cadetblue;
   border: 2px groove green;
   border-radius: 50%;
}
</style>
</head>
<body>
<div><div></div></div>
<span></span>
<script>
let element = document.querySelector('div');
let getStyle = window.getComputedStyle(element);
document.querySelector('span').textContent = ('box-shadow: ' + getStyle.getPropertyValue('box-shadow') + '.');
</script>
</body>
</html>

Output

This will produce the following result −


Advertisements