id and class Attributes
Explore how to apply id and class attributes in HTML to identify elements uniquely or collectively. Understand the rules and differences between these attributes to structure and style your web page effectively, enabling targeted CSS styling and JavaScript interactions.
We'll cover the following...
The id and class attributes can be used to identify specific HTML elements across your HTML page.
The id attribute
The id attribute provides you with the ability to give any element a unique identifier. This identifier can later be used for things like applying specific styles with CSS or capturing input with some Javascript code.
<h1 id="companyName">Educative.io</h1>
Some notes about id usage:
- An
idvalue should only be used for a single element (you will get unexpected behavior if you use the sameidvalue for multiple elements). - An
idvalue must not contain any whitespace. - A single element cannot have multiple
idvalues.
The class attribute
The class attribute is similar to the id attribute in that it is used to identify specific elements. The main distinctions are:
- The same
classvalue can be used across multiple elements. - An element can have multiple
classvalues, separated by whitespaces.
In the example below, the id and class attributes are used to apply CSS styles (hidden) to our HTML document. Take note of the main differences between the two attributes.
Test your understanding
(True or False) An HTML element can have both class and id attributes.
True
False