jQuery css()

jQuery css() method can either be used to set a specified CSS property ( where it sets the CSS property for ALL matched elements) or can be used to return the value of a specified CSS property ( where it returns the CSS property value of the FIRST matched element).

jQuery css() sets or returns the CSS properties for the selected elements.

Syntax:

When it is used to return the value.

css("propertyname")

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head>
<body>
<p style="background-color:yellow">How are you?</p>
<p>How are you?</p>
<button>Click me to know my color.</button>
</body>
</html>

 

When it is used to set a specified CSS property.

css("propertyname","value");

Example2:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "cyan");
});
});
</script>
</head>
<body>
<h2>Hello!</h2>
<p style="background-color:pink">How are you?</p>
<p style="background-color:yellow">How are you?</p>
<p>How are you?</p>
<button>Click me for a change</button>
</body>
</html>

 

When it is used to set multiple CSS properties.

css({"propertyname":"value","propertyname":"value",...});

Example3:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css({"background-color": "cyan", "font-size": "25
});
});
</script>
</head>
<body>
<h2>Hello</h2>
<p style="background-color:red">How are you?</p>
<p style="background-color:yellow">How are you?</p>
<p style="background-color:blue">How are you?</p>
<p>How are you?</p>
<button>Click me for multiple changes.</button>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com