How Can I Set A CSS Property In JQuery With Example

admin_img Posted By Bajarangi soft , Posted On 14-10-2020

In Jquery The css() method sets one or more style properties for the selected elements.so today we discuss how to set css property

How Can I Set A CSS Property In JQuery With Example

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

css("propertyname","value");

Set the background-color value for ALL matched elements

Example(1) 

Step 1:Create index.html file and implement below code.

<div class="well">
    <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 class="btn btn-primary" >Set background-color of p</button>
</div>
 

Step 2:Implement jquery to use css method.

<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("p").css("background-color", "pink");
        });
    });
</script>

Complete Code For Setting A CSS Property In JQuery
<!DOCTYPE html>
<html>
<head>
    <title>How To Set A CSS Property In JQuery With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
    body {
        background: darkolivegreen;
    }
    .blue {
        color: blue;
    }
</style>
<body>
<div class="container">
    <br><br><br>
    <br><br><br>
    <div class="text-center">
        <h2 id="color" style="color: White">Set A CSS Property In JQuery</h2>
    </div>
    <br>
    <br>

    <div class="well">
        <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 class="btn btn-primary" >Set background-color of p</button>
    </div>

</div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("p").css("background-color", "pink");
        });
    });
</script>

Related Post