The id attribute designates a unique identifier for an HTML element. Its value must be unique within the HTML document.
The id attribute is utilized to reference a specific style declaration in a style sheet. Additionally, it enables JavaScript to access and modify the element with the designated id.
The syntax for id is as follows: prepend a hash character (#) followed by the id name. Then, specify the CSS properties within curly braces {}.
In the given example, an <h1> element is associated with the id “myHeader”. This <h1> element will be styled based on the #myHeader style definition in the head section.
Example
<!DOCTYPE html> <html> <head> <style> #myHeader { background-color: lightblue; color: black; padding: 40px; text-align: center; } </style> </head> <body> <h1 id=”myHeader”>My Header</h1> </body> </html> |
Note: The id name is case sensitive! Note: The id name must comprise at least one character, cannot commence with a number, and must be devoid of whitespaces (spaces, tabs, etc.). |
A class name can be shared among multiple HTML elements, whereas an id name must be unique and assigned to only one HTML element on the page.
Example
<style> /* Style the element with the id “myHeader” */ #myHeader { background-color: lightblue; color: black; padding: 40px; text-align: center; } /* Style all elements with the class name “city” */ <!– An element with a unique id –> <h1 id=”myHeader”>My Cities</h1> <!– Multiple elements with same class –> <h2 class=”city”>London</h2> <p>London is the capital of England.</p> <h2 class=”city”>Paris</h2> <p>Paris is the capital of France.</p> <h2 class=”city”>Tokyo</h2> <p>Tokyo is the capital of Japan.</p> |
HTML bookmarks enable readers to navigate directly to specific sections of a webpage.
Bookmarks prove particularly helpful for lengthy pages.
To employ a bookmark, it must first be created, followed by adding a link to it.
Subsequently, clicking the link will prompt the page to scroll to the bookmarked location.
Example
Initially, generate a bookmark utilizing the id attribute.
<h2 id=”C4″>Chapter 4</h2> |
Next, include a link to the bookmark (“Jump to Chapter 4”) within the same page.
Example
<a href=”#C4″>Jump to Chapter 4</a> |
Alternatively, add a link to the bookmark (“Jump to Chapter 4”) from a different page.
<a href=”html_demo.html#C4″>Jump to Chapter 4</a> |
JavaScript has the capability to execute tasks tailored to a particular element through its id attribute.
This is facilitated by the getElementById() method, enabling JavaScript to target and interact with specific elements based on their unique identifiers.
Example
Leverage the id attribute in JavaScript to dynamically alter text content.
<script> function displayResult() { document.getElementById(“myHeader”).innerHTML = “Have a nice day!”; } </script> |