HTML5 Guidelines for Web Developers

(coco) #1

274 Chapter 12—Finishing Touches:Some Global Attributes


The game will consist of an HTML part, a script part, and a CSS part. All three
components are of course available online for experimenting and inspecting.
Here are the links:
z http://html5.komplett.cc/code/chap_global/1234_en.html
z http://html5.komplett.cc/code/chap_global/1234.js
z http://html5.komplett.cc/code/chap_global/1234.css

12.1 News for the “class” Attribute


We first turn to a new DOM method of the HTMLElement interface, which allows
us easy access to elements by the content of their respective class attribute:
document.getElementsByClassName(). Its use could hardly be simpler and looks
like this:

var questions = document.getElementsByClassName('q');

This gives us a list ordered by position in the DOM tree of all elements whose
class attribute contains the value q. If this list happens to consist of li elements
with the names of the capital cities, the first step toward implementing our game
is done: A live reference to the game objects is set in the variable questions. It
reflects the current status of the individual li elements:

<li id=de class=q>Berlin</li>
<li id=at class=q>Vienna</li>
<!-- and 25 others -->

Access to the individual li elements can happen in two ways: either via the offset
in the list or via a name, by which we do not mean the node content but the value
of the existing id or name attribute:

questions.item(1).innerHTML => Vienna
questions.namedItem(‘de’).innerHTML => Berlin

The length of the list can be found in questions.length, which means the offset
for item(i) values can be between 0 and questions.length-1. Instead of an id at-
tribute, elements with name attributes, for example form, can also be searched via
namedItem(str) for values in this attribute.
If you want to search for several classes, you only need to pass the desired values
during the method call, separated by spaces. Using the fictitious example of a
fruit shop, searching for fruit defined as red or apple as their I like criteria could
be successful with the following instruction:

NOTE
Free download pdf