w3resource
jquery exercises

jQuery CSS - Toggle a specified class when an element is clicked

jQuery CSS: Exercise-10 with Solution

Toggle a specified class when an element is clicked.

Sample Data :

HTML :

<body>
<p></p>
</body>

CSS:

<style>
p {
    margin-top:20px;
    margin-left: 10px;
    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>Toggle a specified class when an element is clicked</title>
  <style>
  p {
    margin: 5px;
    font-size: 15px;
    cursor: pointer;
  }

  .highlight {
    background: #F4FA58;
  }
  </style>
</head>
<body>
<p>Click on the Paragraphs</p>
<p>jQuery Exercises</p>
<p>JavaScript Exercises</p>
</body>
</html>

JavaScript Code:

$( "p" ).click(function() {
  $( this ).toggleClass("highlight");
});

Live Demo:

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


Contribute your code and comments through Disqus.

Previous: Find the offset of an element.
Next: jQuery Events Exercises

What is the difficulty level of this exercise?



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