With jQuery we can add class attributes to different elements. We can select single or multiple elements to apply the class to.
In this example, we have a couple of headings and three lines of text.
By clicking the Add Class button, we trigger an event that changes all the text to red. Text line three also increases in size.
Now let's look at the code to see how it works.
$("h1, h2, p").toggleClass("red");
<p>Text Line 1.</p>
<p>Text Line 2.</p>
<div>Text Line 3.</div><br>
First, we can see in our
<body> that we have two heading tags.
We also have two paragraph tags, each containing a line of text.
<div> element contains a third line of text.
Lastly we have our button element.
Our style sheet, has two classes, big and red. The big class will change the font weight to bold and size to x-large.
The red class will change the text color to red.
Neither of these classes is used yet.
In our script tags, we have created a
click event on the button.
click event triggers our
addClass() method, which ads the class "red" to any
<p> elements on the page.
addClass() method is created to add multiple classes (big and red) to any
<div> elements on the page.