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
id
attribute is used in the<h1>
and<button>
elements with values"header"
and"myButton"
, respectively.
- The
-
CSS Styling:
- The
#header
selector 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
id
attribute must be unique within a page. No two elements should have the sameid
value. - Case Sensitivity: The
id
attribute is case-sensitive, somyButton
andMyButton
would be considered different IDs.
Using IDs effectively allows you to target and style specific elements or manipulate them using JavaScript.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.