jQuery: Add a specified class to the matched elements
jQuery Fundamental - I : Exercise-5
Using jQuery add the class " w3r_font_color " to the last paragraph element.
<p>PHP</p> <p>Java</p> <p>Python</p>
p { margin: 8px; font-size: 16px; } .w3r_font_color{ color: red; } .w3r_background { background: yellow; }
Sample solution :
HTML Code :
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Add a specified class to the matched elements.</title>
</head>
<body>
<p>PHP</p>
<p>Java</p>
<p>Python</p>
</body>
</html>
CSS Code:
p {
margin: 8px;
font-size: 16px;
}
.w3r_font_color{
color: red;
}
.w3r_background {
background: yellow;
}
JavaScript Code :
$( "p" ).last().addClass( "w3r_font_color" );
Used Methods :
- .last() : Reduce the set of matched elements to the final one in the set.
- .addClass() : Adds the specified class(es) to each element in the set of matched elements.
See the Pen jquery-fundamental-exercise-5 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Using jQuery add the previous set of elements on the stack to the current set.
Next: Using jQuery add the class "w3r_font_color" and “w3r_background” to the last paragraph element.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics