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.
-
CSS Styling:
- The
#header
selector in the CSS targets the <h1>
element with id="header"
and applies styles to it. The #
symbol denotes that it's an ID selector.
-
JavaScript Interaction:
- The
document.getElementById('myButton')
method is used to select the button with id="myButton"
. The JavaScript code then adds an event listener to the button that displays an alert when the button is clicked.
Important Notes:
- Uniqueness: The value of the
id
attribute must be unique within a page. No two elements should have the same id
value.
- Case Sensitivity: The
id
attribute is case-sensitive, so myButton
and MyButton
would be considered different IDs.
Using IDs effectively allows you to target and style specific elements or manipulate them using JavaScript.