css() | How To Give CSS Properties & Values to an HTML Element in jQuery?

Date Published: 28/04/2020Published By: JaiSchool

Jquery provides us a method to set the properties and value of CSS (cascading style sheet) to an HTML element in Jquery. The method is css().

Syntax to give single property:value of CSS in Jquery

Giving a single property:value of CSS does not need to write it in the curly braces by starting in the css() method's argument.

For single CSS property, you separate property and value with a comma and each should be surrounded in double or single.

See example:-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<h1 id="heading">Jaischool</h1>
<script>
$(document).ready(function(){
 $("#heading").css("color","red");
});
</script>
</body>
</html>

Syntax to give multiple property:value of CSS in Jquery

In respect of giving multiple properties, write them in curly braces. Property and value must be separated by a colon ( : ) and both must be quoted in single or double quotes separately. To define the next property, terminate the first property:value by a comma.

Example:~

<!DOCTYPE html>
<html>
<head>
	<title>Jquery</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<p>Jaischool</p>
<script>
$(document).ready(function(){
  $("p").css({
     "color":"blue",
     "fontSize":"30px"
  });
});
</script>
</body>
</html>

Get the value of CSS property in Jquery

Simply, to know the value of any CSS property applied to the HTML element. Just select the element and then pass the css() method. After that write, only the property name as a parameter you want value for. It will return the value of that property.

See example below~~

$(document).ready(function(){
 var x= $("#heading").css("color");
 alert(x);
});

Publish A Comment

Leave a Reply

Your email address will not be published.