In this article, we get CSS property value in javascript. To do this task we have two methods, the first one is The style property and the second one is getComputedStyle.
Method 1: The Style Property
The style
read-only and retrieves property returns the inline style of an element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div class="className" style="font-size: 2em; color: red;">Hello, Coder</div>
</body>
</html>
Javascript
const element = document.querySelector('.className')
const fontSize = element
console.log(fontSize) // 2em
const color = element.style.color
console.log(color) // red
Result
"2em"
"red"
Method 2: getComputedStyle
The Window.getComputedStyle()
the method returns an object containing the values of all CSS properties of an element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div class="element"> This is my element </div>
<style>
.element { background-color: red }
</style>
</body>
</html>
Javascript
const element = document.querySelector('.element')
const style = getComputedStyle(element)
console.log(style) // red

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.