Open In App
Related Articles

How to get styles of a clicked division using jQuery ?

Improve Article
Improve
Save Article
Save
Like Article
Like

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:

                      


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 31 May, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials