HTML id-Attribut
Das id-Attribut definiert einen eindeutigen Bezeichner für ein HTML-Element, der für Stile, Ankerlinks und Skripte genutzt wird.
Das HTML-Attribut id weist einem Element einen eindeutigen Bezeichner zu. Dieser seitenweite Name ermöglicht es, das Element über CSS anzusprechen, per URL direkt zu verlinken, über JavaScript darauf zuzugreifen und es für Barrierefreiheit zu verknüpfen. Da id ein globales Attribut ist, kann es auf jedem HTML-Element verwendet werden.
Diese Seite behandelt die eine Regel, die nie gebrochen werden darf (Eindeutigkeit), gültige id-Syntax sowie die vier Aufgaben einer id auf echten Seiten: Fragment-Links, CSS-Styling, JavaScript-Selektion und Formular-/Barrierefreiheits-Verknüpfungen. Das id-Attribut gehört zu den globalen Attributen, die jedes Element akzeptiert.
Die Grundregel: Eine id muss eindeutig sein
Ein id-Wert muss im gesamten Dokument eindeutig sein — kein zweites Element darf dieselbe id besitzen. Das ist der entscheidende Unterschied zum class-Attribut, bei dem ein Klassenname auf viele Elemente angewendet werden kann:
id— ein Wert, ein Element. Verwende ihn für das einzelne Objekt auf der Seite (einen bestimmten Abschnitt, ein bestimmtes Formularfeld, die Hauptüberschrift).class— wiederverwendbar, viele Elemente. Verwende sie für eine Gruppe, die gleich aussehen oder sich gleich verhalten soll.
Wenn eine id doppelt vorkommt, wird die Seite zwar noch gerendert, aber Werkzeuge verhalten sich auf unerwartete Weise: getElementById gibt nur das erste Treffer-Element zurück, ein #fragment-Link springt zum ersten Treffer, und CSS-#id-Regeln werden unvorhersehbar angewendet. Validatoren melden doppelte IDs als Fehler.
Gültige id-Syntax
Einige Regeln stellen sicher, dass eine id überall funktioniert:
- Sie muss mindestens ein Zeichen enthalten.
- Sie darf keine Leerzeichen enthalten (Leerzeichen, Tabulatoren, Zeilenumbrüche).
- Sie ist groß- und kleinschreibungssensitiv —
mainundMainsind zwei verschiedene IDs. - Für maximale Kompatibilität sollte der Wert mit einem Buchstaben beginnen (
a–z,A–Z) und nur Buchstaben, Ziffern, Bindestriche (-) und Unterstriche (_) enthalten. IDs, die mit einer Ziffer beginnen, sind in HTML5 gültig, müssen in CSS aber maskiert werden — ein buchstabenbasierter Name ist daher die sichere Wahl.
<!-- 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 -->Syntax
<tag id="id">...</tag>Beispiel des HTML id-Attributs
<!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>Im obigen Beispiel spricht CSS jeden Absatz mit dem #id-Selektor an — einer Raute (#) gefolgt vom id-Wert. Da jede id zu genau einem Element gehört, wird nur dieser Absatz gestylt.
id und class gemeinsam
id und class erscheinen häufig auf demselben Element. Ein gängiges Muster ist die Verwendung einer class für gemeinsames Styling und einer id für das eine Element, auf das man außerdem verlinken oder das man per Skript ansprechen möchte. Im nächsten Beispiel trägt die Überschrift eine eindeutige id, während mehrere Absätze eine wiederverwendbare Klasse teilen:
Beispiel der HTML id- und class-Attribute
<!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>Verlinkung zu einer id (Fragment-Links und Lesezeichen)
Ein Link, dessen href mit # beginnt, ist ein Fragment-Link (auch Anker oder Lesezeichen genannt). Er zeigt auf das Element derselben Seite, dessen id dem Text nach dem # entspricht. Ein Klick darauf scrollt die Seite zu diesem Element — nützlich für lange Seiten, Inhaltsverzeichnisse und „Nach oben"-Links.
<a href="#pricing">Jump to pricing</a>
...
<section id="pricing">...</section>Es ist auch möglich, zu einem Fragment auf einer anderen Seite zu verlinken, indem eine URL mit dem Hash kombiniert wird: <a href="/learn-html/global-attributes#id">…</a>. Wird eine Seite mit einem Fragment in der Adressleiste geöffnet, scrollt der Browser direkt zu diesem Element.
Beispiel zum Hinzufügen eines Lesezeichens
<!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>Eine id mit JavaScript auswählen
Da jede id eindeutig ist, stellt sie den direktesten Weg dar, ein einzelnes Element per Skript anzusprechen. Zwei gängige Ansätze:
<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 erwartet den id-Wert ohne das #, während querySelector den vollständigen CSS-#id-Selektor verwendet. Beide geben nur das erste übereinstimmende Element zurück — ein weiterer Grund, IDs eindeutig zu halten.
Formulare und Barrierefreiheit
IDs sind das Mittel, mit dem Elemente aufeinander verweisen, was sie zu einem zentralen Bestandteil barrierefreier Formulare und der Unterstützung durch Screenreader macht:
<label for="…">verbindet ein Label mit einem Formularfeld, dessenidübereinstimmt. Ein Klick auf das Label fokussiert dann das Eingabefeld, und assistive Technologien lesen das Label vor, wenn das Feld fokussiert wird.aria-labelledby="…"benennt ein Element anhand des Textes eines anderen Elements, das peridreferenziert wird.aria-describedby="…"verweist auf ein Element (perid), das zusätzliche Hilfe oder Fehlermeldungen enthält.- Skip-Links — ein „Zum Inhalt springen"-Link (
href="#main") zeigt auf dieiddes Hauptbereichs, damit Tastaturnutzer die Navigation überspringen können.
<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>Hier referenzieren sowohl for als auch aria-describedby IDs, sodass der Browser weiß, dass Label, Feld und Hilfetext zusammengehören.
Hinweis zur CSS-Spezifität
Der CSS-#id-Selektor ist sehr spezifisch — weit stärker als ein Klassen- oder Element-Selektor. Diese Stärke ist zugleich eine Falle: Regeln, die mit IDs geschrieben werden, sind schwer zu überschreiben und führen zu „Spezifitätskriegen", bei denen man immer mehr Selektoren (oder !important) stapelt. Für wiederverwendbares Styling sind Klassen vorzuziehen; #id-Selektoren sollten wirklich nur einmaligen Fällen vorbehalten bleiben. Einen tieferen Einblick in die Wahl zwischen beiden in Stylesheets bietet CSS id and class.