Атрибут id в HTML
Атрибут id задаёт уникальный идентификатор HTML-элемента для стилей, якорных ссылок и скриптов.
Атрибут HTML id назначает элементу уникальный идентификатор. Это единственное, действующее в рамках всей страницы имя позволяет обращаться к элементу из CSS, формировать прямые ссылки на него в URL, получать его через JavaScript и связывать с ним средства доступности. Поскольку id — глобальный атрибут, его можно добавить к любому HTML-элементу.
На этой странице рассматривается единственное правило, которое нельзя нарушать (уникальность), допустимый синтаксис id, а также четыре задачи, которые id решает на реальных страницах: ссылки на фрагменты, стилизация через CSS, выбор элемента через JavaScript и связывание форм с элементами доступности. Атрибут id входит в состав глобальных атрибутов, которые принимает каждый элемент.
Главное правило: id должен быть уникальным
Значение id должно быть уникальным в пределах всего документа — два элемента не могут иметь одинаковый id. Это ключевое отличие от атрибута class, где одно имя класса можно использовать повторно на множестве элементов:
id— одно значение, один элемент. Применяйте его для единственного объекта на странице (конкретный раздел, определённое поле формы, главный заголовок).class— многократного использования, для многих элементов. Применяйте его для группы элементов с одинаковым внешним видом или поведением.
Если продублировать id, страница по-прежнему отобразится, но инструменты начнут работать некорректно: getElementById вернёт только первое совпадение, ссылка #fragment перейдёт к первому совпадению, а CSS-правила вида #id будут применяться непредсказуемо. Валидаторы отмечают дублирующиеся идентификаторы как ошибки.
Допустимый синтаксис id
Несколько правил гарантируют корректную работу id во всех случаях:
- Значение должно содержать хотя бы один символ.
- Значение не должно содержать пробельных символов (пробелы, табуляция, переносы строк).
- Значение чувствительно к регистру —
mainиMain— это два разных идентификатора. - Для максимальной совместимости начинайте значение с буквы (
a–z,A–Z) и используйте только буквы, цифры, дефисы (-) и подчёркивания (_). Идентификаторы, начинающиеся с цифры, допустимы в HTML5, но требуют экранирования в CSS, поэтому имя, начинающееся с буквы, — более надёжный выбор.
<!-- 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 -->Синтаксис
<tag id="id">...</tag>Пример атрибута 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>В приведённом примере CSS обращается к каждому абзацу через селектор #id — символ решётки (#) с последующим значением идентификатора. Поскольку каждый идентификатор принадлежит ровно одному элементу, стиль применяется только к этому абзацу.
id и class вместе
Атрибуты id и class часто используются на одном элементе. Распространённый паттерн — применять class для общей стилизации, а id — для единственного элемента, на который нужно сослаться или которым нужно управлять через скрипт. В следующем примере заголовок имеет уникальный id, тогда как несколько абзацев используют общий класс:
Пример атрибутов id и 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>Ссылки на id (ссылки на фрагменты и закладки)
Ссылка, у которой значение href начинается с #, является ссылкой на фрагмент (также называемой якорем или закладкой). Она указывает на элемент той же страницы, чей id совпадает с текстом после #. При нажатии страница прокручивается к этому элементу — что удобно для длинных страниц, оглавлений и ссылок «вернуться наверх».
<a href="#pricing">Jump to pricing</a>
...
<section id="pricing">...</section>Можно также ссылаться на фрагмент другой страницы, совместив URL с хэшем: <a href="/learn-html/global-attributes#id">…</a>. При открытии страницы с фрагментом в адресной строке браузер сразу прокручивает её до нужного элемента.
Пример добавления закладки
<!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>Выбор элемента по id через JavaScript
Поскольку каждый id уникален, это самый прямой способ получить доступ к одному конкретному элементу в скрипте. Два распространённых подхода:
<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 принимает значение идентификатора без символа #, тогда как querySelector использует полный CSS-селектор вида #id. Оба метода возвращают только первый совпадающий элемент — это ещё одна причина сохранять уникальность идентификаторов.
Формы и доступность
Идентификаторы — это способ, которым элементы ссылаются друг на друга, что делает их ключевыми для доступных форм и поддержки программ чтения с экрана:
<label for="…">связывает метку с элементом управления формы, чейidсовпадает. Нажатие на метку переводит фокус на поле ввода, а вспомогательные технологии зачитывают метку при фокусировке на поле.aria-labelledby="…"именует элемент, используя текст другого элемента, указанного по егоid.aria-describedby="…"указывает на элемент (поid), содержащий дополнительную подсказку или текст об ошибке.- Ссылки-пропуски — ссылка «Перейти к содержимому» (
href="#main") указывает наidосновной области, позволяя пользователям клавиатуры пропустить навигацию.
<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>Здесь атрибуты for и aria-describedby ссылаются на идентификаторы, благодаря чему браузер понимает, что метка, поле и поясняющий текст связаны между собой.
Замечание о специфичности CSS
Селектор CSS #id обладает очень высокой специфичностью — значительно большей, чем у класса или элементного селектора. Однако эта мощь таит в себе ловушку: правила, написанные с использованием идентификаторов, сложно переопределить, что ведёт к «войнам специфичности», когда приходится нагромождать всё больше селекторов (или использовать !important), чтобы добиться нужного результата. Для повторно используемых стилей предпочтительнее классы; селекторы #id оставляйте для действительно уникальных случаев. Подробнее о выборе между ними в таблицах стилей см. в разделе CSS id и class.