Using jQuery with an ID Selector

Clicking the button below will change the background and foreground colour of the element whose ID is "change_me" (the paragraph above the button), using the selector #change_me, just as in CSS. Clicking a second time will change it 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> $(document).ready(function(){ $("#button").click(function(){ $("#change_me").toggleClass("new_colours"); return false; }); }); </script>

In this example, we've added the script to the head of our HTML file but it would be better to save it as a separate file with a .js extension and then load it with a script tag.

Here's the markup for the target:

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

And the markup for the trigger button:

   <input type="button" value="Make Change" id="button" />

And the CSS rule that is toggled on and off:

.new_colours {

Notice that we have managed to make our JavaScript completely unobtrusive (i.e. there is absolutely no inline scripting), we are using only class and id selectors to make the whole thing work. This is part of the beauty of jQuery and enables us to add behaviour to our web pages whilst keeping the behavioural layer separate from the structural layer.

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.

When the button above is clicked, the paragraph in this document with the id "change_me" will have the class "new_colours" added and when the button is clicked again, the "new_colours" class is removed - it's a toggle.

If we wanted to change lots of paragraphs at the same time, we could use a class selector instead of the id selector. Remember, IDs are unique elements but classes are not. So, just as with CSS, we use ID selectors to target unique elements and class selectors to target many elements.