The id attribute specifies a unique id for an HTML element (this value must be unique within the HTML document). Refer to the following article by Mytour for detailed understanding of the id attribute in HTML.
The id attribute in HTML
1. HTML ID Attribute
2. Difference Between Class and ID Attributes in HTML
3. Creating Bookmarks in HTML
4. Using the ID Attribute in JavaScript
1. HTML ID Attribute
CSS and JavaScript can utilize the id value to perform specific tasks for the element with the assigned id value.
In CSS, to select a specific id element, we use the pound sign (#) followed by the id of the element.
For instance:
The returned result looks like this:
Note:
- The id attribute can be used on any HTML element.
- The id value must be written in uppercase letters.
- The id value must contain at least one character and cannot contain whitespace (spaces, tabs, ...).
2. What are the differences between class and id attributes in HTML?
Each HTML element can have only one unique id, whereas a class name can be used by multiple elements.
Example: Refer to the example below to understand the differences between the class and id attributes in HTML:
The returned result looks like this:
3. Creating Bookmarks in HTML
Bookmarks in HTML are used to allow readers to navigate to specific sections on a web page.
Bookmarks are particularly useful, especially on long web pages.
To create a bookmark in HTML, first we need to define a bookmark, then add a link to that bookmark.
When users click on the link, the page will scroll to the position where the bookmark is located.
Example: In the example below, we will create a bookmark in HTML:
First, we use the id attribute to create a bookmark:
The next step is to add a link to the bookmark (jump to chapter 4) on the same page:
Or add a link to the bookmark (jump to chapter 4) from another page:
The returned result looks like this:
4. Utilizing the id Attribute in JavaScript
JavaScript can access an element with a specified id using the getElementById() method.
Example: In the example below, we utilize the id attribute to manipulate text using JavaScript:
The returned result looks like this:
So in the above article, Mytour just introduced you to the id attribute in HTML. Additionally, if you have any doubts or questions that need clarification, readers can leave their comments below the article.
In the next article, Mytour will further introduce you to the color attribute in HTML.