jQuery - css() Method
jQuery css() Method
The css() function can change or show the style of certain parts on a webpage.
Return a CSS Property
To get the value of a particular CSS property, use this format:
This example will give you the background color of the FIRST matching element:
Set a CSS Property
To apply a particular CSS style, use this format:
css("propertyname","value");
Here's an example that changes the background color for all elements that match the specified criteria:
Set Multiple CSS Properties
To apply various CSS styles, use this format:
css({"propertyname":"value","propertyname":"value",...});
The next example will define a background color and text size for EVERY element that matches.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>
<button>Return background-color of p</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>
<p>This is a paragraph.</p>
<button>Set background-color of p</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").css({
"background-color": "yellow",
"font-size": "200%"
});
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>
<p>This is a paragraph.</p>
<button>Set multiple styles for p</button>
</body>
</html>