Element.attributes
La proprietà Element.attributes
restituisce una raccolta in tempo reale di tutti i nodi di attributo registrati nel nodo specificato. È una NamedNodeMap
, non un Array
, quindi non ha metodi predefiniti degli Array
e non ha i metodi Attr
dei nodi che possono differire tra i browser. Per essere più specifici, attributes
è una coppia chiave/valore di stringhe che rappresenta qualsiasi informazione riguardante quell'attributo.
Sintassi
var attr = element.attributes;
Esempio
Esempi basilari
// Ottenere il primo elemento <p> nel documento
var para = document.getElementsByTagName("p")[0];
var atts = para.attributes;
Enumerazione degli attributi degli elementi
L'indicizzazione numerica è utile per passare attraverso tutti gli attributi di un elemento.
L'esempio seguente esegue i nodi dell'attributo per l'elemento nel documento con id "paragraph" e stampa il valore di ciascun attributo.
<!DOCTYPE html>
<html>
<head>
<title>Attributes example</title>
<script type="text/javascript">
function listAttributes() {
var paragraph = document.getElementById("paragraph");
var result = document.getElementById("result");
// First, let's verify that the paragraph has some attributes
if (paragraph.hasAttributes()) {
var attrs = paragraph.attributes;
var output = "";
for(var i = attrs.length - 1; i >= 0; i--) {
output += attrs[i].name + "->" + attrs[i].value;
}
result.value = output;
} else {
result.value = "No attributes to show";
}
}
</script>
</head>
<body>
<p id="paragraph" style="color: green;">Sample Paragraph</p>
<form action="">
<p>
<input type="button" value="Show first attribute name and value"
onclick="listAttributes();">
<input id="result" type="text" value="">
</p>
</form>
</body>
</html>
Specifiche
Specifica | Stato | Commento |
---|---|---|
DOM The definition of 'Element.attributes' in that specification. |
Living Standard | Da Document Object Model (DOM) Level 3 Core Specification, spostato da Node a Element |
Document Object Model (DOM) Level 3 Core Specification The definition of 'Element.attributes' in that specification. |
Obsolete | Nessun cambiamento da Document Object Model (DOM) Level 2 Core Specification |
Document Object Model (DOM) Level 2 Core Specification The definition of 'Element.attributes' in that specification. |
Obsolete | Nessun cambiamento da Document Object Model (DOM) Level 1 Specification |
Document Object Model (DOM) Level 1 Specification The definition of 'Element.attributes' in that specification. |
Obsolete | Definizione iniziale. |
Compatibilità con i browser
BCD tables only load in the browser
Vedi anche
NamedNodeMap
, l'interfaccia dell'oggetto restituito- Considerazioni sulla compatibilità con ross-browser: su quirksmode