jQuery css() Method
The jQuery css() method is used to get the computed value of a CSS property or set one or more CSS properties for the selected elements.
This method provides a quick way to apply the styles directly to the HTML elements (i.e. inline styles) that haven’t been or can’t easily be defined in a stylesheet.
Get a CSS Property Value
You can get the computed value of an element’s CSS property by simply passing the property name as a parameter to the css() method. Here’s the basic syntax:
$(selector).css(“propertyName”);
The following example will retrieve and display the computed value of the CSS background-color property of a <div> element, when it is clicked.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery css() Demo</title>
<style>
div{
width: 100px;
height: 100px;
display: inline-block;
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
var color = $(this).css("background-color");
$("#result").html(color);
});
});
</script>
</head>
<body>
<div style="background-color:orange;"></div>
<div style="background-color:#ee82ee;"></div>
<div style="background-color:rgb(139,205,50);"></div>
<div style="background-color:#f00;"></div>
<p>The computed background-color property value of the clicked DIV element is: <b id="result"></b></p>
</body>
</html>