HTML id attribute का उपयोग किसी element को uniquely identify करने के लिए किया जाता है।
एक HTML page में एक ही id सिर्फ एक element को दी जा सकती है।
id Attribute क्या होता है
id एक global attribute है जो किसी भी HTML element पर apply किया जा सकता है।
यह element को uniquely target करने के लिए use होता है।
id का main purpose:
JavaScript से element select करना
CSS में specific element style करना
Page bookmarks और links बनाना
id Attribute का Basic Syntax
<div id="header">
Website Header
</div>
यह “header” id वाला element uniquely identify करता है।
CSS के साथ id का उपयोग
CSS में id selector # से define किया जाता है।
<style>
#header {
background-color: lightgray;
padding: 15px;
}
</style>
यह style सिर्फ उसी element पर apply होगी।
JavaScript के साथ id का उपयोग
JavaScript में id से element select करना सबसे common है।
<script>
document.getElementById("header").innerHTML = "New Header";
</script>
यह सीधे specific element को target करता है।
id और Anchor Links
id का use page के अंदर jump links बनाने में भी होता है।
<a href="#section1">Go to Section 1</a>
<div id="section1">
Content here
</div>
Click करने पर page उसी section पर scroll हो जाएगा।
id Attribute और Forms
Forms में label और input को connect करने के लिए id use होती है।
<label for="username">Username</label>
<input type="text" id="username">
यह accessibility के लिए बहुत जरूरी है।
id vs class में Difference
id:
Unique होती है
एक element के लिए
Specific targeting
class:
Reusable होती है
Multiple elements के लिए
Grouping के लिए
id Naming Rules
id name में:
Spaces नहीं होने चाहिए
Unique होना चाहिए
Meaningful नाम होना चाहिए
Correct:id="main-content"
Wrong:id="main content"
id और CSS Specificity
id selectors की specificity class selectors से ज्यादा होती है।
इसलिए id से दी गई styling आसानी से override नहीं होती।
Multiple ids Allowed नहीं हैं
एक element पर सिर्फ एक id दी जा सकती है।
और same id दो elements पर नहीं हो सकती।
Common Mistakes
Same id multiple elements पर देना
Styling के लिए unnecessary id use करना
JavaScript और CSS में confusion
id naming inconsistent रखना
Best Practices
id का use unique elements के लिए करें
Layout styling के लिए class prefer करें
Meaningful naming रखें
Accessibility को ध्यान में रखें
Summary
HTML id attribute element को uniquely identify करने के लिए use होता है।
यह CSS, JavaScript और anchor links के लिए बहुत important है।
Proper id usage clean, accessible और maintainable code सुनिश्चित करता है।
