w3resource

jQuery: Add two classes to the matched elements

jQuery Fundamental - I : Exercise-6

Using jQuery add the class "w3r_font_color" and “w3r_background” to the last paragraph element.

<p>PHP</p>
<p>Java</p>
<p>Python</p>
p {
    margin: 8px;
    font-size: 16px;
  }
.w3r_font_color{
    color: blue;
  }
.w3r_background {
    background: orange;
  }
 

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 two classes 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: blue;
  }
.w3r_background {
    background: orange;
  }

JavaScript Code :


$( "p" ).last().addClass( "w3r_font_color w3r_background " );

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

Go to:


PREV : Using jQuery add the class " w3r_font_color " to the last paragraph element.
NEXT : Using jQuery add a new class to an element that already has a class.

See the Pen jquery-fundamental-exercise-6 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.