HTML ID

In HTML, the `id` attribute is used to uniquely identify an element within a document. Unlike classes, which can be shared by multiple elements, an `id` must be unique within the HTML document. The `id` attribute is used to uniquely identify and target specific elements for styling or scripting purposes. Here's how you can use the `id` attribute in HTML:


1. Defining an ID:

To define an ID for an element, you use the `id` attribute and assign it a unique name. The name should be meaningful and descriptive. It's recommended to use lowercase letters and hyphens or underscores to separate words in the ID for better readability.

html
<h1 id="page-title">Welcome to my website!</h1>
<div id="content">This is the main content area.</div>

2. Targeting elements with CSS:

CSS can be used to target and style elements based on their `id`. To select elements based on their ID, you use the hash (`#`) notation followed by the ID name in your CSS rules.

css
#page-title {
    color: blue;
    font-size: 24px;
}

In the above example, the `h1` element with the `id` of "page-title" will have blue text color and a font size of 24 pixels.


3. Accessing elements with JavaScript:

JavaScript can be used to access and manipulate elements based on their `id`. You can use the `getElementById()` method to retrieve a reference to the element with the specified `id`.

javascript
var pageTitle = document.getElementById("page-title");
pageTitle.textContent = "New Title";

The JavaScript code above selects the element with the `id` "page-title" and changes its content to "New Title".


The `id` attribute is primarily used to uniquely identify elements within a document and is often used for specific element targeting, such as navigation links, header elements, or form inputs. Remember to ensure that each `id` in your HTML document is unique to avoid conflicts.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext