mardi 21 août 2012

Rechercher un élément récurcivement dans l'arbre DOM

Pour le fun, aujourd'hui, voici un code qui recherche un input à partir d'une balise.
La recherche se fait dans la balise pour dans les parents, jusqu'à arriver au document lui même (root.parentNode == null).
function chercherInput(nom, root) {
    // Remonte jusqu'a trouve l'input
    var allRows = root.getElementsByTagName('input') ;
    var item = null ;

    while ((root != null) && (item == null)) {
        for (var i = 0; i < allRows.length; i++) {
            if (allRows[i].name.match(nom) != null) {
                item = allRows[i] ;
                break ;
            }
        }

        root = root.parentNode ;
        allRows = root.getElementsByTagName('input') ;
    }

    return item ;  
}

function selectNumber(root) {
    var item = chercherInput('^toto\\[[0-9]+\\]\\.numero$', root) ;

    if (item != null) {
        item.value = 'coucou' ;
    }
}
Code HTML :
<div onclick="selectNumber(this)">Cliquez moi !</div>

Aucun commentaire:

Enregistrer un commentaire