Open In App

How to get styles of a clicked division using jQuery ?

Last Updated : 31 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to get the styles (width, height, text color, and background color) of a clicked division using jQuery.

Approach: The css() method is used to get the CSS property values of the selected element in jQuery. We use the css() method in jQuery that takes an array of names of properties and return an array of values of that properties. We store this array and use it for displaying the CSS of all the clicked div’s.

Syntax:

var styles = $(this).css([
    "width",
    "height",
    "color",
    "background-color",
]);

Example: The following code demonstrates the above approach. Refer to the output for better understanding. On click of one div, it shows the width, height, color, and background-color properties and their respective values.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <style>
        div {
            height: 50px;
            margin: 5px;
            padding: 5px;
        }
  
        #htmlDivID {
            width: 300px;
            color: yellow;
            background-color: blue;
        }
  
        #cssDivID {
            width: 310px;
            color: green;
            background-color: grey;
        }
  
        #jQueryDivID {
            width: 320px;
            color: pink;
            background-color: blue;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">
        GeeksforGeeks
    </h2>
  
    <b>
        Click to see the div
        element's styles
    </b>
  
    <div id="htmlDivID">HTML</div>
    <div id="cssDivID">CSS</div>
    <div id="jQueryDivID">jQuery</div>
    <br />
  
    <div id="displayID"></div>
  
    <script>
        $("div").click(function () {
            var cssValues = [];
  
            var styles = $(this).css([
                "width",
                "height",
                "color",
                "background-color",
            ]);
            $.each(styles, function (prop, value) {
                cssValues.push("<b>" + prop 
                    + "</b>: " + value + ", ");
            });
  
            $("#displayID").show().html(cssValues);
        });
    </script>
</body>
  
</html>


 

Output:

  • Before clicking on div:

            

  • After clicking on div:

                      



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads