HTML5 Guidelines for Web Developers

(coco) #1

276 Chapter 12—Finishing Touches:Some Global Attributes


12.3 The “hidden” Attribute


In the HTML Working Group, the hidden attribute caused a great stir. It managed
to reach ISSUE status with a following Straw Poll for Objections and only got its
final blessing through a decision of the HTML Working Group chairmen. The
critics mainly claimed that hidden is superfluous. We will shortly demonstrate
that the hidden attribute can indeed be useful, because selecting the questions
for our game will be done via hidden. The algorithm is quickly explained: We first
hide all items with hidden and then reveal four randomly selected items again.
The relevant JavaScript code looks like this:

var showRandomNItems = function(q,n) {
var show = [];
for (var i=0; i<q.length; i++) {
q.item(i).hidden = true;
show.push(i);
}
show.sort(function() {return 0.5 – Math.random()});
for (var i=0; i<n; i++) {
q.item(show[i]).hidden = false;
}
};

As arguments, we pass the list with li elements in the variable q and the desired
number of elements to be shown in n to the function showRandomNItems(). We then
hide all items with hidden=true and fill a new array with the indices of 0 – q.length.
This array is then put in random order, and the desired number n of capital cities
is revealed again.

12.4 The “classList” Interface


With getElementsByClassName(), we have already encountered the first option of
working with the global class attribute. The classList interface is another one,
allowing us to manage all values of a class attribute in a so-called DOMTokenList
via the methods item(), contains(), add(), remove(), and toggle(). Let’s again
use the example of the class attribute of a product in our fictitious fruit shop:

<li class="red apple">

Via li.classList, we then have the following properties:

li.classList.length => 2
li.classList.item(0) => red
Free download pdf