w3resource

jQuery: Get the styles of a clicked division

jQuery Fundamental - II : Exercise-64

Get the styles (width, height, text color, and background color) of a clicked division.

 <body>
 <p  id="result">&nbsp;</p>
 <div  id="box1">A</div>
 <div  id="box2">B</div>
 <div  id="box3">C</div>
 </body>
 

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Get the styles (width, height, text color, and background color) of a clicked division.</title>
</head>
<body>
<p id="result">&nbsp;</p>
<div id="box1">A</div>
<div id="box2">B</div>
<div id="box3">C</div>
</body>
</html>

CSS Code :

 div {
 height: 50px;
 margin: 5px;
 padding: 5px;
 float: left;
 }
 #box1
 width: 50px;
 color: yellow;
 background-color: red;
 }
 #box2 
 width: 50px;
 color: rgb(255, 255, 255);
 background-color: rgb(15, 99, 30);
 }
 #box3 {
 width: 50px;
 color: #fcc;
 background-color: #123456;
 }
 p {
 color: blue;
 }

JavaScript Code :

$( "div" ).click(function() {
var html = [ "The clicked div has the following styles:" ];
var styleProps = $( this ).css([
"width", "height", "color", "background-color"
]);
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});

$( "#result" ).html( html.join( "<br>" ) );
});

See the Pen jquery-fundamental-exercise-64 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Get the background color of a clicked division.
Next: Change the color of any paragraph to red on mouseover event.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/2/jquery-fundamental-exercise-64.php