set class in XHTML1 Strict
set class in XHTML1 Strict to demonstrate potential logic for jQuery
by mpedrotti
HTML
<h4>Test of statement to set class attribute value in XHTML1 Strict</h4>
<p>For <strong>span</strong> elements which have the following initial class attributes, set the value to <strong>strong</strong> using the following statement:
<br />if (typeof elem.className === "string") { elem.className = value; } else { elem.setAttribute("class", value); }</p>
<table id="resultsHTML">
<thead>
<tr><th>span</th><th colspan="2">.className</th></tr>
<tr><th>class="…"</th><th>typeof</th><th>value</th></tr>
</thead>
<tbody>
<tr>
<th><span>no class attribute</span></th>
</tr>
<tr>
<th><span class="">empty class attribute</span></th>
</tr>
<tr>
<th><span class="strong">strong</span></th>
</tr>
<tr>
<th><span class="emphasis">emphasis</span></th>
</tr>
<tr>
<th><span class="strong emphasis">strong emphasis</span></th>
</tr>
</tbody>
</table>
CSS
* { margin-top: 0; margin-bottom: 0; }
body { line-height: 1; font-family: Helvetica, Verdana, sans-serif; }
h4 { margin-top: 1em; margin-bottom: 1em; }
.strong { font-weight: bold; }
.emphasis { font-style: italic; }
table { margin-top: 1em; }
th { text-align: left; }
table tbody th { width: 15em; font-weight: normal; }
JavaScript
(function ($) {
function td(text) {
return '<td>' + text + '</td>';
}
function table($table, selector) {
$table.find('tbody tr').each(function () {
var $tr = $(this), elem = $tr.find(selector).get(0), typeofClass = typeof elem.className, value = elem.className;
$tr.append(td(typeofClass)).append(td(value));
if (typeofClass === "string") { elem.className = "strong"; } else { elem.setAttribute("class", "strong"); }
});
}
table($('#resultsHTML'), 'span');
}(jQuery));