ID Attribute in HTML - Beginner Friendly Guide
What is the ID Attribute in HTML?
The id attribute is used to give a unique name to an HTML element. This name (the ID) can be used to
identify, style, or access that element using CSS or JavaScript.
Important Points About ID Attribute:
- An ID must be unique on a page - only one element can have that ID.
- It helps us to:
- Apply CSS to one specific element.
- Use JavaScript to change that specific element.
- Jump to a section using links (#id).
Syntax:
<tag id="yourID">Content</tag>
Example:
<p id="myParagraph">This is a paragraph with an ID.</p>
1. Using ID with CSS:
Style one specific element using a hash symbol (#) in CSS.
#myParagraph { color: green; font-size: 20px; }
2. Using ID with JavaScript:
Access or modify the element using getElementById.
document.getElementById("myParagraph").style.color = "blue";
3. Using ID for Navigation (Anchor link):
Create links that jump to sections of the page.
<a href="#about">Go to About Section</a>
<p id="about">Welcome to the About Section!</p>
Rules for ID Attribute:
- Must start with a letter (A-Z or a-z).
- No spaces allowed.
- Should not be repeated on the same page.
When to Use ID:
- To target one specific element.
- When using JavaScript or CSS for one item.
- For creating jump links to parts of a page.