get class in XHTML4 Transitional
get class in HTML4 Transitional to demonstrate potential logic for jQuery
HTML
<h4>Test of expression to get class attribute value in HTML4 Transitional</h4>
<p>For <strong>span</strong> elements which have the following class attributes, the values could be computed by either of the following expressions:
<br />1) typeof elem.className === "string" ? elem.className : elem.getAttribute("class") ? elem.getAttribute("class") : ""
<br />2) typeof elem.className === "string" ? elem.className : typeof elem.getAttribute("class") === "string" ? elem.getAttribute("class") : ""</p>
<table id="resultsHTML">
<thead>
<tr><th>span</th><th colspan="2">computed</th><th colspan="2">.className</th><th colspan="2">getAttribute("class")</th></tr>
<tr><th>class="…"</th><th>1) value</th><th>2) value</th><th>typeof</th><th>value</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, expected) {
return '<td>' + text + '</td>';
}
function table($table, selector) {
$table.find('tbody tr').each(function () {
var $tr = $(this), elem = $tr.find(selector).get(0);
$tr
.append(td(typeof elem.className === "string" ? elem.className : elem.getAttribute("class") ? elem.getAttribute("class") : ""))
.append(td(typeof elem.className === "string" ? elem.className : typeof elem.getAttribute("class") === "string" ? elem.getAttribute("class") : ""))
.append(td(typeof elem.className))
.append(td(elem.className))
.append(td(typeof elem.getAttribute("class")))
.append(td(elem.getAttribute("class")));
<p>djdjjf</p>
});
}
table($('#resultsHTML'), 'span');
}(jQuery));