set class in HTML5 which contains SVG

set class in HTML5 which contains SVG to demonstrate potential logic for jQuery

by mpedrotti

HTML

<h4>Test of statement to set class attribute value in HTML5 which contains SVG</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 === &quot;string&quot;) { elem.className = value; } else { elem.setAttribute(&quot;class&quot;, value); }</p>
<p><strong>Important:</strong> If this was XHTML5 (that is, served as XML in addition to having the HTML5 DOCTYPE), the .className columns for SVG <strong>text</strong> in the second table would be <strong>object</strong> and <strong>[object SVGAnimatedString]</strong>, therefore <strong>else</strong> would apply.</p>
<table id="resultsHTML">
<thead>
<tr><th>span</th><th colspan="2">.className</th></tr>
<tr><th>class=&quot;&#x2026;&quot;</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>
<table id="resultsSVG">
<thead>
<tr><th>text</th><th colspan="2">.className</th></tr>
<tr><th>class=&quot;&#x2026;&quot;</th><th>typeof</th><th>value</th></tr>
</thead>
<tbody>
<tr>
<th>
<svg version="1.1" viewBox="0 0 150 10" preserveAspectRatio="xMinYMin meet" xml:lang="en" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<style type="text/css">
text { font-size: 10px; }
</style>
<text x="0" y="8">no class attribute</text>
</svg>
</th>
</tr>
<tr>
<th>
<svg version="1.1" viewBox="0 0 150 10" preserveAspectRatio="xMinYMin meet" xml:lang="en" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<style type="text/css">
text { font-size: 10px; }
</style>
<text x="0" y="8" class="">empty class...

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');
table($('#resultsSVG'), 'text');
}(jQuery));