Using jQuery with a Class Selector

Clicking the button below will change the background and foreground colour of all the elements whose class is "change_me" (the paragraphs above and below the button), using the selector .change_me, just as in CSS. Clicking a second time will change them back again (a toggle). This example uses the jQuery .toggleClass() function to toggle a class on and off. The class rule can be as simple or as complex as we want, so spectacular changes to an element can be made without any additional JavaScript.

Here's the script that does the work:

<!-- load jQuery from Google CDN -->
<script src="
jquery.min.js"></script> <script> $(function(){ $("#button").click(function(){ $(".change_me").toggleClass("new_colours"); return false; }); }); </script>

Here's the markup for the target:

<p class="change_me">Lorem ipsum dolor sit amet…</p>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec non sem at sapien vulputate fringilla. Curabitur leo leo, tincidunt eu placerat vitae, venenatis ac sem. Ut a dapibus eros. Cras ut imperdiet leo. Nulla fermentum, turpis nec commodo sodales, nibh eros varius diam, sed commodo eros nibh vel est. Etiam sollicitudin lobortis ipsum, et vehicula velit accumsan ut. Ut tempus est id neque pharetra sodales. Cras scelerisque sem non urna aliquam imperdiet. Proin consectetur eleifend diam, quis tempor libero tincidunt in.

Duis sed ligula odio, sed posuere magna. Integer facilisis interdum hendrerit. Nunc eleifend tempus facilisis. Nunc mattis erat ut justo scelerisque sed convallis lorem ultricies. Proin convallis vehicula tincidunt. Fusce ac sapien et odio consectetur condimentum et id elit. Suspendisse potenti. Aliquam erat volutpat. Mauris sollicitudin aliquam lacus, sit amet commodo nisl ornare sed. In tristique, mauris at auctor gravida, tellus nibh dapibus elit, nec cursus purus nisl faucibus magna. Morbi feugiat pulvinar pretium.

If we wanted more specificity, we could even use a selector such as p.change_me so that the function would then be:

		return false;

Essentially, we can use the same selectors with jQuery that we use with CSS.

Note: In this example, the script is shown as it would appear if placed in the HTML file and is done only for convenience in demonstrating how it works. The best practice solution would be to place the script in an external file and call it like this:

<script src="filename.js"></script>

jQuery selectors work in exactly the same way as CSS selectors, so the script will work just as well from an external .js file as it will from the .html file.