W3docs

Attributo id HTML

L'attributo id definisce un identificatore univoco per un elemento HTML, usato per stili, link ancorati e script.

L'attributo HTML id assegna un identificatore univoco a un elemento. Quel nome unico a livello di pagina ti permette di selezionare l'elemento da CSS, di collegarlo direttamente tramite un URL, di recuperarlo con JavaScript e di configurarlo per l'accessibilità. Poiché id è un attributo globale, puoi applicarlo a qualsiasi elemento HTML.

Questa pagina tratta l'unica regola che non devi mai infrangere (l'unicità), la sintassi valida per id, e i quattro ruoli che un id svolge nelle pagine reali: link a frammenti, stilizzazione CSS, selezione con JavaScript e associazioni con form/accessibilità. L'id fa parte degli attributi globali che ogni elemento accetta.

La regola fondamentale: un id deve essere univoco

Un valore id deve essere univoco all'interno dell'intero documento — nessun elemento può condividere lo stesso id con un altro. Questa è la differenza principale rispetto all'attributo class, in cui un nome di classe può essere riutilizzato su più elementi:

  • id — un valore, un elemento. Usalo per l'elemento unico sulla pagina (una sezione specifica, un campo di form particolare, il titolo principale).
  • class — riutilizzabile, su più elementi. Usala per un gruppo che deve avere lo stesso aspetto o comportamento.

Se duplichi un id, la pagina continua a essere visualizzata, ma gli strumenti si comportano in modo imprevedibile: getElementById restituisce solo la prima corrispondenza, un link #fragment salta alla prima corrispondenza e le regole CSS #id si applicano in modo imprevedibile. I validatori segnalano gli id duplicati come errori.

Sintassi valida per id

Alcune regole garantiscono che un id funzioni correttamente ovunque:

  • Deve avere almeno un carattere.
  • Non deve contenere spazi (spazi, tabulazioni, interruzioni di riga).
  • È sensibile alle maiuscolemain e Main sono due id diversi.
  • Per la massima compatibilità, inizia il valore con una lettera (az, AZ) e usa solo lettere, cifre, trattini (-) e underscore (_). Gli id che iniziano con una cifra funzionano in HTML5 ma richiedono un escape in CSS, quindi un nome che inizia con una lettera è la scelta più sicura.
<!-- Good -->
<div id="main-content"></div>
<section id="pricing"></section>

<!-- Avoid -->
<div id="main content"></div>   <!-- space is invalid -->
<div id="2col"></div>           <!-- digit-first: awkward in CSS -->

Sintassi

<tag id="id">...</tag>

Esempio dell'attributo id HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #grey {
        color: grey;
      }
      #purple {
        color: purple;
      }
    </style>
  </head>
  <body>
    <h1>Example of the HTML id attribute</h1>
    <p id="grey">
      It is a grey paragraph.
    </p>
    <p>This is some text.</p>
    <p id="purple">
      It is a purple paragraph.
    </p>
  </body>
</html>

Nell'esempio precedente, CSS seleziona ogni paragrafo con il selettore #id — un cancelletto (#) seguito dal valore dell'id. Poiché ogni id appartiene a esattamente un elemento, viene stilizzato solo quel paragrafo.

id e class insieme

id e class compaiono spesso sullo stesso elemento. Uno schema comune è usare una class per la stilizzazione condivisa e un id per l'unico elemento a cui devi anche collegarti o su cui agire con uno script. Nell'esempio seguente, il titolo ha un id univoco mentre diversi paragrafi condividono una classe riutilizzabile:

Esempio degli attributi id e class HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #green-bg {
        background-color: green;
        color: white;
        padding: 20px;
        text-align: center;
      }
      .text-grey {
        color: grey;
        padding: 5px 15px;
      }
    </style>
  </head>
  <body>
    <h1>Example of the HTML "id" and "class" attributes:</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <h2 id="green-bg">HTML ID attribute</h2>
    <p class="text-grey">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.
    </p>
    <p class="text-grey">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book
    </p>
    <p class="text-grey">
      The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Un link il cui href inizia con # è un link a frammento (chiamato anche ancora o segnalibro). Punta all'elemento nella stessa pagina il cui id corrisponde al testo dopo il #. Cliccandoci sopra la pagina scorre fino a quell'elemento — utile per pagine lunghe, indici e link "torna all'inizio".

<a href="#pricing">Jump to pricing</a>
...
<section id="pricing">...</section>

Puoi anche collegarti a un frammento su un'altra pagina combinando un URL con il cancelletto: <a href="/learn-html/global-attributes#id">…</a>. Aprire una pagina con un frammento nella barra degli indirizzi scorre direttamente a quell'elemento.

Esempio di aggiunta di un segnalibro

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        line-height: 1.5;
        color: #777777;
      }
      a {
        color: #20c7c1;
        display: inline-block;
        padding: 5px 15px;
      }
      strong {
        display: block;
        color: #1129dc;
      }
    </style>
  </head>
  <body>
    <h1>Example of the HTML "id" and "class" attributes:</h1>
    <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.</p>
    <a href="#text2">Jump to the text-2</a>
    <a href="#text3">Jump to the text-3</a>
    <p id="text-1">
      <strong>Text number 1</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.
    </p>
    <p id="text2">
      <strong>Text number 2</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book
    </p>
    <p id="text3">
      <strong>Text number 3</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      <strong>Text number 4</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      <strong>Text number 5</strong> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Selezionare un id con JavaScript

Poiché ogni id è univoco, è il modo più diretto per raggiungere un singolo elemento in uno script. Due approcci comuni:

<button id="save-btn">Save</button>

<script>
  // Fastest, dedicated method for ids:
  const btn = document.getElementById("save-btn");

  // querySelector uses the CSS #id selector (note the hash):
  const sameBtn = document.querySelector("#save-btn");

  btn.addEventListener("click", () => {
    console.log("Saved!");
  });
</script>

getElementById accetta il valore dell'id senza il #, mentre querySelector usa il selettore CSS #id completo. Entrambi restituiscono solo il primo elemento corrispondente, il che è un motivo in più per mantenere gli id univoci.

Form e accessibilità

Gli id sono il modo in cui gli elementi si riferiscono l'uno all'altro, il che li rende fondamentali per i form accessibili e il supporto agli screen reader:

  • <label for="…"> collega un'etichetta a un controllo del form il cui id corrisponde. Facendo clic sull'etichetta si sposta il focus sull'input e la tecnologia assistiva annuncia l'etichetta quando il campo è selezionato.
  • aria-labelledby="…" assegna un nome a un elemento usando il testo di un altro elemento referenziato dal suo id.
  • aria-describedby="…" punta a un elemento (tramite id) che fornisce ulteriore aiuto o testo di errore.
  • Link di salto — un link "Salta al contenuto" (href="#main") punta all'id della regione principale affinché gli utenti da tastiera possano bypassare la navigazione.
<label for="email">Email address</label>
<input type="email" id="email" aria-describedby="email-help">
<p id="email-help">We'll never share your email.</p>

Qui for e aria-describedby referenziano entrambi degli id, quindi il browser sa che l'etichetta, il campo e il testo di aiuto appartengono insieme.

Una nota sulla specificità CSS

Il selettore CSS #id è altamente specifico — molto più forte di un selettore di classe o di elemento. Questo potere è anche una trappola: le regole scritte con gli id sono difficili da sovrascrivere e portano a "guerre di specificità" in cui si accumulano più selettori (o !important) per avere la meglio. Per la stilizzazione riutilizzabile, preferisci le classi; riserva i selettori #id ai casi davvero unici. Per un'analisi più approfondita su come scegliere tra i due nei fogli di stile, consulta CSS id e class.

Esercitati

Pratica
Quale affermazione sull'attributo HTML 'id' è corretta?
Quale affermazione sull'attributo HTML 'id' è corretta?
Was this page helpful?