HTML ID
In HTML, the id attribute is used to assign a unique identifier to an HTML element. This unique identifier can then be used to reference the element in CSS for styling, or in JavaScript for manipulating the element.
Here’s a basic example of how the id attribute is used in HTML:
Example 1: Basic Usage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML ID Example</title>
<style>
/* CSS styling using ID */
#header {
color: blue;
font-size: 24px;
}
</style>
</head>
<body>
<h1 id="header">Welcome to My Website</h1>
<p>This is a paragraph of text.</p>
<button id="myButton">Click Me!</button>
<script>
// JavaScript accessing element by ID
document.getElementById('myButton').addEventListener('click', function() {
alert('Button was clicked!');
});
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- The
idattribute is used in the<h1>and<button>elements with values"header"and"myButton", respectively.
- The
-
CSS Styling:
- The
#headerselector in the CSS targets the<h1>element withid="header"and applies styles to it. The#symbol denotes that it's an ID selector.
- The
-
JavaScript Interaction:
- The
document.getElementById('myButton')method is used to select the button withid="myButton". The JavaScript code then adds an event listener to the button that displays an alert when the button is clicked.
- The
Important Notes:
- Uniqueness: The value of the
idattribute must be unique within a page. No two elements should have the sameidvalue. - Case Sensitivity: The
idattribute is case-sensitive, somyButtonandMyButtonwould be considered different IDs.
Using IDs effectively allows you to target and style specific elements or manipulate them using JavaScript.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
