Manipulating Class Names (^) ❘ 97
Manipulating Class Names
In earlier chapters, you’ve seen examples of the addClass(), hasClass(), removeClass(), and
toggleClass() methods that jQuery uses to manipulate class names.
It is considered best practice in client-side web development to avoid placing style declarations
directly in your JavaScript code and instead maintain a separation of behavior and presentation
by placing styles in CSS and manipulating the class names of elements for situations in which you
require a dynamic change of style. This is considered best practice for a reason: It keeps things
neatly organized and obvious; you don’t need to search for style changes in JavaScript or HTML,
only in the style sheets. Because all your presentation is neatly contained in CSS, your behaviors
in JavaScript, and your structure in HTML, your documents become easier to manage because it’s
more predictable where to look to make a modifi cation. If your styles are scattered inline in HTML,
in the JavaScript, and in style sheets, then it becomes an order of magnitude more diffi cult to change
the presentation of a document because now you have to track down which document contains the
change. No big deal for a small web page, but when you scale up to a large website or application,
those conventions come into play.
The following example demonstrates the four methods jQuery provides to manipulate and check for
the existence of one or more class names. This example appears in the source code download mate-
rials from http://www.wrox.com/go/webdevwithjquery as Example 4-2.
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />
<title>John Lennon Albums</title>
<script src='../jQuery.js'></script>
<script src='../jQueryUI.js'></script>
<script src='Example 4-2.js'></script>
<link href='Example 4-2.css' rel='stylesheet' />
</head>
<body>
<form action='javascript:void(0);' method='get'>
<h4>John Lennon Albums</h4>
<table>
<thead>
<tr>
<th>Title</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Lennon/Plastic Ono Band</td>
<td> 1970 </td>
</tr>
<tr>
<td>Imagine</td>
<td> 1971 </td>