Introduction
HTML Id is essential for providing a unique identifier to elements within a document. This identifier plays a crucial role in styling through CSS and dynamic manipulation using JavaScript.
Syntax
<tag id="value">
HTMLExample 1: CSS Styling
Styling an element with the id “main-heading” in CSS:
<!DOCTYPE html>
<html>
<head>
<style>
#main-heading {
font-size: 24px;
color: #3498db;
text-align: center;
margin-bottom: 20px;
}
#sub-heading {
font-size: 18px;
color: #2ecc71;
text-align: center;
}
</style>
</head>
<body>
<h1 id="main-heading">Welcome to our Website</h1>
<h2 id="sub-heading">Exploring the World of Coding</h2>
</body>
</html>
HTMLExample 2: JavaScript Interaction
Using the id attribute in JavaScript to validate a form:
<!DOCTYPE html>
<html>
<head>
<title> Form Validation </title>
<script>
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (name === "" || email === "") {
alert("Name and Email are required!");
return false;
}
alert("Form submitted successfully!");
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
Name: <input type="text" id="name">
<br>
Email: <input type="email" id="email">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
HTMLDifference Between Class and ID in HTML
- Class: Used by multiple HTML elements.
- ID: Must be unique within the document.
HTML Bookmarks with ID and Links
Creating bookmarks for navigation within a page:
<h2 id="section1">Section 1</h2>
<a href="#section1">Jump to Section 1</a>
HTMLConclusion
This attribute provides a unique identifier for elements, enabling targeted styling and dynamic JavaScript interactions. Remember, it must be unique within the document, and its case sensitivity should be considered.
Frequently Asked Questions
Ans: No, an HTML element can have only one id’s attribute. It must be unique within the document.
2. Is the id attribute case-sensitive?
Ans: Yes, the id attribute is case-sensitive. “myId” and “myID” are considered different.
3. Can I use the id’s attribute on any HTML element?
Ans: Yes, the id’s attribute is versatile and can be used on any HTML element.