Atrybut identyfikatora HTML


Przykład

Użyj atrybutu id, aby manipulować tekstem za pomocą JavaScript:

<html>
<body>

<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>

<script>
function displayResult() {
  document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>

</body>
</html>

Więcej przykładów „Wypróbuj sam” poniżej.


Definicja i użycie

idAtrybut określa unikalny identyfikator elementu HTML (wartość musi być unikalna w dokumencie HTML) .

Atrybut jest idnajczęściej używany do wskazywania stylu w arkuszu stylów, a przez JavaScript (poprzez HTML DOM) do manipulowania elementem o określonym identyfikatorze.


Obsługa przeglądarki

Attribute
id Yes Yes Yes Yes Yes

Składnia

<element id="id">

Wartości atrybutów

Value Description
id Specifies a unique id for the element. Naming rules:
  • Must contain at least one character
  • Must not contain any space characters

Więcej przykładów

Przykład 1

Użyj atrybutu id, aby połączyć się z elementem o określonym identyfikatorze na stronie:

<html>
<body>

<h2><a id="top">Some heading</a></h2>

<p>Lots of text....</p>
<p>Lots of text....</p>
<p>Lots of text....</p>

<a href="#top">Go to top</a>

</body>
</html>

Przykład 2

Użyj atrybutu id, aby stylizować tekst za pomocą CSS:

<html>
<head>
<style>
#myHeader {
  color: red;
  text-align: center;
}
</style>
</head>
<body>

<h1 id="myHeader">W3Schools is the best!</h1>

</body>
</html>

Powiązane strony

Samouczek HTML: identyfikator HTML

Samouczek HTML: atrybuty HTML

Samouczek CSS: składnia CSS

Dokumentacja CSS: CSS #id Selector

Dokumentacja HTML DOM: Metoda HTML DOM getElementById()

Odniesienie HTML DOM: Właściwość identyfikatora HTML DOM

Dokumentacja HTML DOM: Obiekt stylu HTML DOM