Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

jQuery CSS - Add a class to an element

jQuery CSS : Exercise-2 with Solution

Add the following class "myclass" to the matched paragraph elements.

Sample Data :

HTML :

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

CSS :

<style>
  p {
      margin: 8px;
	  font-size: 16px;
	}
 .myclass 
    {
	 color: #FA5858;
	}  
.highlight 
  {
    background: #CEF6F5;
  }
 </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>Add a class to an element</title>
  <style>
  p {
    margin: 10px;
    font-size: 22px;
  }
  .myclass {
    color: #FA5858;
  }
  .highlight {
    background: #CEF6F5;
  }
  </style>
</head>
<body>
<p>jQuery Exercises</p>
<p>and Solution.</p>
 </body>
</html>

JavaScript Code:

$( "p" ).first().addClass( "highlight" );
$( "p" ).last().addClass( "myclass" );

Live Demo:

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


Contribute your code and comments through Disqus.

Previous: Get the background color of an element.
Next: Find the widths and heights of various elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.