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.
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/jquery-css-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics