Lister les libellés d'un document

Nous allons apprendre à lister les libellés d'un document HTML à l'aide du DOM niveau 2 (noyau et HTML). On se reposera essentiellement sur document.getElementsByTagName. Cette méthode, je cite, Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree..

Qu'est-ce qu'une NodeList ? C'est une interface d'énumération de nœuds. La spécification la décrit ainsi :

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

The items in the NodeList are accessible via an integral index, starting from 0.

Voici le code nécessaire. Par simplicité, on suppose qu'une fonction getInnerText existe :

function printLabelsInfo() {
    var msg = '';
    var labels = document.getElementsByTagName('label');
    for (var index = 0; index < labels.length; ++index) {
        var label = labels[index];
        msg += getInnerText(label);
        if (label.hasAttribute('for') &&
                document.getElementById(label.htmlFor))
            msg += ' ->' + label.htmlFor;
        if (label.hasAttribute('accesskey'))
            msg += ' (Alt+' + label.accessKey)';
        msg += '\n';
    }
    alert(msg);
} // printLabelsInfo

Sauvegardez ce code dans un fichier labels.js. Vous remarquez qu'il est de faible taille :

$ ls -l
total 4
-rw-r--r-- 1 demo demo  530 2006-08-23 16:58 labels.js
$