HTML Id Attribute - HTML Tutorial

HTML Id Attribute

BLUF: Mastering HTML Id Attribute is a fundamental step in becoming a web developer. This guide covers the structure, syntax, and best practices for using this HTML element effectively.
Key Lesson: HTML Id Attribute

Web structure starts with solid HTML. Learn how HTML Id Attribute contributes to accessible and semantic web pages in the tutorial below.

The HTML identifier attribute assigns a unique name to an element within the document. This identifier can be utilized by CSS and JavaScript to precisely target the element for styling and behavior manipulation purposes.

The id must be unique in the entire HTML document. The same id cannot be used twice. id is a global attribute, i.e., it can be applied to any HTML element. The id value is case sensitive. Some naming conventions are in place:

  • Must have no fewer than one character
  • One cannot start with a number
  • One cannot contain whitespace characters
  • Syntax

Example

<tag id="value"> </tag>

Using id in CSS

One commonly used feature of the id attribute in CSS involves assigning styles to a specific, unique element.

Syntax

Example

#idName {

  /* CSS properties */

}

Note: Target the element using the hash (#) symbol and the value of id.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <style>

    #highlight {

      background-color: yellow;

      font-weight: bold;

      text-align: center;

    }

  </style>

</head>

<body>

  <p id="highlight">This paragraph is uniquely styled.</p>

</body>

</html>

Output:

Output

Paragraph will appear with yellow background, bold text, and centred alignment.

Explanation

The element identified with the id "highlight" can be customized by using the #highlight { ... } selector, demonstrating the precision of id selectors within CSS.

Using id in JavaScript

In JavaScript, it is recommended to access elements using DOM variables and the id attribute.

Syntax

Example

document.getElementById("idValue")

Example

Example

<!DOCTYPE html>

<html>

<head>

  <script>

    function changeText() {

      document.getElementById("message").innerHTML = "Hello, World!";

    }

  </script>

</head>

<body>

  <h2 id="message">Original Text</h2>

  <button onclick="changeText()">Change Text</button>

</body>

</html>

Output:

Output

Upon clicking the button, the heading text updates to: "Hello, World!"

Explanation

The script identifies the element having the id "message" and then proceeds to update its content using the innerHTML property.

id vs. class Attributes

While both id and class can be utilized for selecting elements, they differ significantly in the following aspects:

Feature id Attribute class Attribute
Uniqueness Must be unique on a page Can apply to multiple elements
Syntax in CSS #idValue { … } .className { … }
Use case Target a single element Style or script groups of elements

Note: Id is ideal when used in an unusual element (e.g., major navigation bar), and class is excellent when a similar style is required for many items.

HTML Bookmarks (Fragment Navigation)

The id attributes can also serve to define page anchors, which are commonly referred to as bookmarks or fragment identifiers.

Syntax

Example

<h2 id="section1">Section 1</h2>

<a href="#section1">Jump to Section 1</a>

Example

Example

<!DOCTYPE html>

<html>

<body>

  <h2 id="intro">Introduction</h2>

  <p>Content...</p>

  <a href="#intro">Back to Introduction</a>

</body>

</html>

Output:

Output

Clicking the link scrolls to the heading marked with id="intro".

Explanation:

The anchor with the identifier (#intro) enables internal navigation within the same page by linking to the element identified by that specific ID.

Best Practices

It is advisable to enclose your identifier values in double quotation marks, for example, id="myId". While certain browsers may still recognize unquoted values, using quoted values is more dependable and helps avoid unexpected issues. Additionally, refrain from starting an identifier with a numeral, like id="item_one", as this does not conform to the correct syntax for an HTML identifier. Another important practice is to steer clear of duplicating identifiers on a single page.

There are situations where browsers might consider only the final occurrence of an id that is being utilized. This behavior can lead to inconsistencies or unexpected outcomes when the same id is repeated multiple times. It is important to note that ids are frequently utilized in URLs for navigation purposes. They are identified as #idValue and can be customized or controlled using CSS by utilizing the pseudo-class :target.

Examples of Advanced Usage

1. Scrolling Into View (JavaScript)

Example

Example

<!DOCTYPE html>

<html>

<body>

  <div id="sectionA" style="margin-top: 500px;">Far below</div>

  <button onclick="document.getElementById('sectionA').scrollIntoView();"> Go down </button>

</body>

</html>

Output:

Output

By clicking the button, the page scrolls down to the element with the id="sectionA".

Explanation

The scrollIntoView function enables direct navigation to a specified element by its unique identifier (id).

2. Highlighting Target Using CSS :target

Example

Example

<!DOCTYPE html>

<html>

<head>

  <style>

    :target {

      background-color: lightyellow;

      border: 2px solid gold;

    }

  </style>

</head>

<body>

  <h2 id="part1"> Part 1 title </h2>

  <p> Content for part 1 as a paragraph. </p>

  <a href="#part1"> This highlights Part 1 </a>

</body>

</html>

Output:

Output

By clicking the link, the id="part1" is highlighted specially.

Explanation

The CSS pseudo-class :target is utilized to apply styles to the element within a URL fragment.

3. Using id for Form Label Association

The id attribute plays a crucial role in HTML forms by linking a label with its corresponding input field. This linkage enhances the accessibility and usability of the form, allowing users to easily navigate between the label and the input field by clicking on the label.

Example

Example

<!DOCTYPE html>

<html>

<body>

  <form>

    <label for="email"> Email Address: </label>

    <input type="email" id="email" name="email">

    <button type="submit"> Submit </button>

  </form>

</body>

</html>

Output:

Output

The text label Email Address: is also a hyperlink, and when clicked, it will automatically focus the email input field.

Explanation

The for attribute here corresponds to the input id (id="email"), providing assistance to screen readers and enhancing the interactivity of forms.

Summary of Key Points

The HTML id attribute plays a crucial role in uniquely identifying an element within a webpage. This attribute is essential for ensuring proper interactions with CSS and JavaScript. It is important to note that each id must be unique, as having the same id for multiple elements can lead to unpredictable behavior.

Naming an identifier (id) requires following certain conventions: the id is case-sensitive, must not contain spaces, and should not begin with a number. It is recommended to enclose id values in quotes. The id attribute is commonly utilized for applying specific styles, enabling scripting functionalities, and creating in-page navigation elements or bookmarks.

Conclusion

The id attribute plays a crucial role in front-end development within HTML. It is essential for precise CSS styling, JavaScript manipulation, and seamless navigation within fragment links. Utilizing the id attribute correctly involves following rules, ensuring uniqueness, and adopting modern practices such as :target or scrollIntoView.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience