Metodo HTML DOM hasAttribute()
❮ L'oggetto elementoEsempio
Scopri se un elemento <button> ha un attributo onclick:
var x = document.getElementById("myBtn").hasAttribute("onclick");
Altri esempi "Provalo da solo" di seguito.
Definizione e utilizzo
Il metodo hasAttribute() restituisce true se l'attributo specificato esiste, altrimenti restituisce false.
Suggerimento: usa setAttribute() per aggiungere un nuovo attributo o modificare il valore di un attributo esistente su un elemento.
Supporto browser
I numeri nella tabella specificano la prima versione del browser che supporta completamente il metodo.
Method | |||||
---|---|---|---|---|---|
hasAttribute() | Yes | 9.0 | Yes | Yes | Yes |
Sintassi
element.hasAttribute(attributename)
Parametri
Parameter | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute you want to check if exists |
Dettagli tecnici
Valore di ritorno: | Un valore booleano, restituisce true se l'elemento ha attributi, altrimenti false |
---|---|
Versione DOM | Oggetto elemento di livello 2 di base |
Altri esempi
Esempio
Scopri se un elemento <a> ha un attributo target. In tal caso, cambia il valore dell'attributo target in "_self":
// Get the <a> element with id="myAnchor"
var x = document.getElementById("myAnchor");
// If the <a> element has a target attribute, set the value to "_self"
if (x.hasAttribute("target")) {
x.setAttribute("target", "_self");
}
Pagine correlate
Esercitazione HTML: attributi HTML
Riferimento HTML DOM: metodo getAttribute()
Riferimento HTML DOM: metodo removeAttribute()
Riferimento HTML DOM: metodo setAttribute()
❮ L'oggetto elemento