Search⌘ K
AI Features

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 id value should only be used for a single element (you will get unexpected behavior if you use the same id value for multiple elements).
  • An id value must not contain any whitespace.
  • A single element cannot have multiple id values.

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 class value can be used across multiple elements.
  • An element can have multiple class values, 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.

  • HTML
html
Implementation of class attribute in HTML

Test your understanding

1.

(True or False) An HTML element can have both class and id attributes.

A.

True

B.

False


1 / 4