FUNZIONI - getElementsByClassName()


<-- Indietro


E' una funzione che non esiste in JS. Permette di recuperare tutti gli elementi, in una nostra pagina, che contengono una determinata classe CSS.
Il funzionamento è simile alla funzione JS getElementsByTagName.
La funzione accetta due parametri:

Il codice č stato visto come prototype dell'oggetto HTMLElement:
HTMLElement.prototype.getElementsByClassName = function( class, tag ){
    var elements = this.getElementsByTagName( tag || "*" );
    var returnElements = [];
    for ( var i = 0; i < elements.length; i++ ){
        if ( elements[i].className.match( new RegExp( "\\b" + class + "\\b" ) ) ) {
            returnElements.push(elements[i]);
        }
    }
    
    return returnElements;
}

document.getElementsByClassName = function ( class, tag ) {
    return document.body.getElementsByClassName( class, tag );
}

La sintassi di utilizzo della funzione è
    elemento.getElementsByClassName("classe che cerco", "tag specifico");

Un esempio di come puņ essere utilizzato:
    var el = document.getElementsByClassName('test');
    if ( el.length ) {
        for ( var j = 0; j < el.length; j++ ) {
            alert(el[j].id);
        }
    } else {
        alert('Non trovato');
    }
    
    // oppure
    if ( ! document.getElementById('menu').getElementsByClassName('selezionato').length ) {
        alert("Nessun elemento selezionato nel menu");
    }

<-- Indietro