jQuery - SPLessons

Chapter 9

jQuery CSS

jQuery CSS

jQuery largely operates using CSS3 selectors.jQuery CSS is used to get and set CSS styles to HTML elements using css() method.

In contrast to jQuery id’s, classes are meant to be applied to one or many elements on the page. This makes it easy to locate collections or sets of elements that either require styling in the context of CSS, or manipulation in the context of jQuery.

jQuery CSS methods does not modify the content and is used to style the HTML elements.

jQuery CSS methods have different syntax and various tasks are performed by these methods.

css(name) Method

The method css(name) fetches or returns to the properties value on matched element.

$(selector).css(name);


<html>
 	<head>
 	 	<title>jQuery CSS</title>
 	</head>
 	
	<body>
 	 	 
		<h3>Click on the box to return background color.</h3>
 	 	<div style="width:300px;height:100px;background:#00A9EC"></div>
			<p>Here Display the Boxes background Color.</p>
			
 	</body>
</html>


$(document).ready(function(){
  $("div").click(function(){
   $("p").html($(this).css("background-color"));
  });
});

Output:

css(name,value) Method

The method css(name,value) is used to set the single property value on matched element.

$(selector).css(name,value);

<html>
	<head>
	   <title>jQuery CSS</title>
	</head>

	<body>
 
		<h1>Welcome to SPLessons</h1>
		<div>
			<p>This is a paragraph</p>
		</div>

	</body>
</html>

$(document).ready(function() {
      $("p").css("background-color","#00A9EC");
 });

Output:

css({properties}) Method

The method css({properties}) is used to set one or more properties values on matched elements.

$(selector).css({properties});


$(document).ready(function() {
      $("p").css({"background-color":"#00A9EC","color":"#fff","font-size":"200%"});
 });

Output:

Summary

  • The method css(name) fetches or returns to the properties value on matched element.
  • The method css(name,value) is used to set the single property value on matched element.
  • The method css({properties}) is used to set one or more properties values on matched elements.