HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

HTML Id Attribute

The id attribute in HTML is used to provide a unique identifier for a specific element on a webpage. The id attribute value must be unique within the entire HTML document, meaning no other element in the same document can have the same id. This uniqueness makes it a powerful tool for targeting and styling specific elements, as well as for scripting and linking purposes.

Here's the basic syntax for adding an id attribute to an HTML element:

Example

<tagname id="uniqueIdentifier">Content goes here <tagname>

You can click on above box to edit the code and run again.

Output

Content goes here

  • <tagname>: Represents the HTML element you want to assign an id to (e.g., <div>,<p> , </h1>, etc.).
  • id="uniqueIdentifier": The id attribute, where you provide a unique identifier for the element.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML id Attribute Example</title>
<style>
        /* CSS styles for illustration purposes */
        #uniqueDiv {
            background-color: #f0f0f0;
            padding: 10px;
        }
</style>
</head>
<body>

<div id="uniqueDiv">
<p>This is a div with a unique id.</p>
</div>
</body>
</html>

You can click on above box to edit the code and run again.

Output

This is a div with a unique id.

  • The <div> element has an id attribute with the value "uniqueDiv."
  • The CSS style block includes a rule for styling the element with the id "uniqueDiv." Styles defined for this id will be applied to this specific <div> element.

Common Uses of the id Attribute:

Styling:

Targeting specific elements for styling using CSS.

JavaScript and DOM Manipulation:

Identifying and manipulating elements using JavaScript.

Anchors and Links:

Creating hyperlinks that link to a specific element on the same page using the # symbol followed by the element's id

Example

<a href="#uniqueDiv"> Jump to Unique Div <a>

You can click on above box to edit the code and run again.

Output

Form Controls:

Associating labels with form controls using the for attribute.

Example

<lable for="username"> username </lable>
<input type="text"id="username" name="username">
            
You can click on above box to edit the code and run again.

Output

username

It's important to use the id attribute responsibly and ensure that each id is unique within the HTML document. Overusing id attributes can lead to maintenance challenges, and classes are often preferred when applying styles or scripting to multiple elements with similar characteristics.