w3resource

jQuery CSS - Get the background color of an element

jQuery CSS: Exercise-1 with Solution

Get the background color of an element.

Click on the following paragraphs and get the background color.

Sample Data :

HTML :

 <body>
<p>jQuery Exercises</p>
<p>and Solution.</p>
</body>
 

CSS :

<style>
 div {
    width: 60px;
    height: 60px;
    margin: 5px;   
  }
  p {
    margin-top:20px;
    padding: 5px;
    border: 2px solid #666;
  }
 </style>

Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Get the background color of an element</title>
    <style>
  div {
    width: 60px;
    height: 60px;
    margin: 5px;   
  }
  p {
    margin-top:20px;
    padding: 5px;
    border: 2px solid #666;
  }
  </style>
</head>
<body>
<div style="background-color:red;"></div>
<div style="background-color:rgb(16,99,30);"></div>
<div style="background-color:#523456;"></div>
<div style="background-color:#a11;"></div>
  <p></p>
</body>
</html>

JavaScript Code:

$( "div" ).click(function() {
  var color = $( this ).css( "background-color" );
  $( "p" ).html( "That div is " + color + "." );
});

Live Demo:

See the Pen jquery-css-exercise-1 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: jQuery CSS Exercises
Next: Add the following class "myclass" to the matched paragraph elements.

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://www.w3resource.com/jquery-exercises/jquery-css-exercise-1.php