Introduction:

  • In this article we will explain how to set css style of selected html elements using jquery or What is css() method in jquery or why use css() method in jquery with example.

 

Description:

The jQuery CSS() method is used to get or set style properties or values for selected html elements.


  • Get a CSS Property value

To return the value of a specified CSS property, use the following syntax:

css("propertyname");

Example:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Example of jQuery </title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#txtbgcolor').val($("#content").css("background-color"));
        });
    </script>
 
</head>
<body>
    
    <div id="content" style="background-color:#9ad506; width:300px;">
        The Lorem Ipsum Generator (DefaultText) provides an elegant and quick way
        to generate default text or Lorem Ipsumto complement your amazing design.
     </div>
    <div style="margin-top:10px;">
        background-Color: <input id="txtbgcolor" type="text" />
    </div>
        
</body>
</html>

Output:

set css property using jquery


In above example we have a div and a textbox we get the div background-color value and that value set in textbox.

 


Set a CSS Property


To set a specified CSS property, use the following syntax:

css("propertyname","value");


Example:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Example of jQuery </title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#content").css("background-color", "#9ad506")
            $("#content1").css("background-color", "#05a32f")
        });
    </script>
 
</head>
<body>
    
    <div id="content" style="width:300px;">
        The Lorem Ipsum Generator (DefaultText) provides an elegant and quick way
        to generate default text or Lorem Ipsum to complement your amazing design.
     </div>
 
    <div id="content1" style="width:300px; margin-top:10px;">
        The Lorem Ipsum Generator (Default Text) provides an elegant and quick way
        to generate default text or Lorem Ipsum to complement your amazing design.
    </div> 
        
</body>
</html>

Output:

set css property using jquery


In above example we have two div that set the different  background-color of both div using jquery.


  • Set Multiple CSS Properties

To set multiple CSS properties, use the following syntax:

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

 

Example:

 

$("#content").css({ "background-color": "#05a32f", "border":"2px solid #ccc"});

 

I hope this article will help to you.


0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like