jquery exercises

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.

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

Sample solution :

HTML Code :

<!DOCTYPE html>
<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>
<p id="result">&nbsp;</p>
<div id="box1">A</div>
<div id="box2">B</div>
<div id="box3">C</div>

CSS Code :

 div {
 height: 50px;
 margin: 5px;
 padding: 5px;
 float: left;
 width: 50px;
 color: yellow;
 background-color: red;
 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?

New Content: Composer: Dependency manager for PHP, R Programming