How To Return A CSS Property In JQuery With Example

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

In Jquery css() method returns one or more style properties for the selected elements. So today we discuss how to return css property

How To Return A CSS Property In JQuery With Example

syntax:

css("propertyname");

Example will return the background-color value of the FIRST matched element:

Example(1)

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

<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>

<button class="btn btn-primary">Return background-color of p</button>


Step 2:Implement jquery to use css method.

<script>
    $(document).ready(function(){
        $("button").click(function(){
            alert("Background color = " + $("p").css("background-color"));
        });
    });
</script>


Complete Code For Returning A CSS Property In JQuery
<!DOCTYPE html>
<html>
<head>
    <title>How To Return 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">Return A CSS Property In JQuery</h2>
    </div>
    <br>
    <br>

    <div class="well">
        <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>

        <button class="btn btn-primary">Return background-color of p</button>

    </div>

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

Related Post