JavaScript getAttribute(): leggere gli attributi HTML
element.getAttribute(nome) legge un attributo HTML come stringa e restituisce null se manca. Lo stato attuale di un campo può differire dal markup. Per leggerlo usa proprietà DOM come checked o value.
Verificare la sintassi e il valore restituito
const link = document.getElementById("guide");
if (link !== null) {
const href = link.getAttribute("href");
console.log(href);
}
Chiama getAttribute() sull’elemento. Se getElementById() restituisce null, controlla il selettore e il momento di esecuzione. Il DOM, Document Object Model, descrive la pagina tramite oggetti. Un elemento mancante è diverso da un attributo mancante.
Distinguere un attributo vuoto da uno assente
const title = element.getAttribute("title");
if (title === null) {
console.log("The title attribute is missing.");
} else if (title === "") {
console.log("The title attribute is empty.");
} else {
console.log(title);
}
if (title) considera falsi sia la stringa vuota sia null. Usa hasAttribute() per verificare solo la presenza. data-* contiene stringhe. Con dataset, data-user-id corrisponde a dataset.userId.
Confrontare href e checked in un esempio completo
Salva il codice come get-attribute.html e aprilo. Il link punta a un titolo dello stesso documento. La casella è selezionata e lo script segue gli elementi.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Read HTML attributes and state</title>
</head>
<body>
<h1>Read attributes</h1>
<p><a id="guide" href="#details" title="" data-count="3">Go to details</a></p>
<label><input id="agree" type="checkbox" checked> Acknowledge notice</label>
<pre id="output"></pre>
<h2 id="details">Details</h2>
<p>Uncheck and recheck the box to compare the results.</p>
<script>
const guide = document.getElementById("guide");
const agree = document.getElementById("agree");
const output = document.getElementById("output");
function render() {
output.textContent = [
`href attribute: ${guide.getAttribute("href")}`,
`href property: ${guide.href}`,
`title: ${JSON.stringify(guide.getAttribute("title"))}`,
`missing aria-label: ${JSON.stringify(guide.getAttribute("aria-label"))}`,
`data-count type: ${typeof guide.getAttribute("data-count")}`,
`checked attribute: ${JSON.stringify(agree.getAttribute("checked"))}`,
`current checked: ${agree.checked}`
].join("\n");
}
agree.addEventListener("change", render);
render();
</script>
</body>
</html>
In partenza l’attributo href vale #details, title vale "", aria-label assente restituisce null e data-count ha tipo string. La proprietà href risolve l’indirizzo rispetto all’URL di base. Deselezionando la casella, checked diventa false e l’attributo rimane vuoto. Prova a rimuovere title="" e ricaricare.
Mostrare gli attributi come testo
Una referenza come < diventa < durante il parsing. Usa textContent per mostrare il valore come testo. setAttribute() e removeAttribute() modificano gli attributi. Per lo stato del modulo usa la proprietà pertinente.
const label = element.getAttribute("data-label");
output.textContent = label ?? "";
Convertire un attributo in un conteggio conservando lo zero
Lancia il codice nella console dell’esempio. Clona il link e accetta solo interi decimali non negativi. Controlla la stringa senza spazi ai bordi prima di chiamare Number() e Number.isSafeInteger().
{
const example = document.querySelector("#guide").cloneNode();
function readCount(element) {
const raw = element.getAttribute("data-count");
if (raw === null || !/^[0-9]+$/.test(raw.trim())) return null;
const count = Number(raw);
return Number.isSafeInteger(count) ? count : null;
}
console.log(readCount(example)); // 3
example.setAttribute("data-count", "0");
console.log(readCount(example)); // 0
example.setAttribute("data-count", " ");
console.log(readCount(example)); // null
example.removeAttribute("data-count");
console.log(readCount(example)); // null
}
L’output è 3, 0, null e null. Gli spazi da soli non diventano zero. I valori negativi, frazionari, esadecimali o fuori dall’intervallo sicuro danno null. Verifica count === null per conservare un vero zero.




