Geek Slack

Introduction to HTML
    About Lesson



    HTML id Attribute


    HTML id Attribute

    The id attribute in HTML is used to specify a unique identifier for an HTML element. The value of the id attribute must be unique within the HTML document.

    1. Basic Usage of the id Attribute

    To use the id attribute, add it to an HTML element with a unique identifier.

    Example:

    This paragraph is highlighted with a yellow background.

    <div id="highlight">
        <p>This paragraph is highlighted with a yellow background.</p>
    </div>

    2. Styling with the id Attribute

    The id attribute can be used in CSS to apply styles to a specific element.

    Example:

    This text is styled with a unique ID.

    <style>
        #unique-style {
            color: blue;
            font-size: 1.5em;
        }
    </style>
    
    <p id="unique-style">This text is styled with a unique ID.</p>

    3. Using id with JavaScript

    You can use the id attribute to select and manipulate elements in JavaScript.

    Example:

    This div’s background color can be changed using JavaScript.

    <button onclick="document.getElementById('highlight').style.backgroundColor = 'lightgreen';">Change Background Color</button>
    <div id="highlight">
        <p>This div's background color can be changed using JavaScript.</p>
    </div>

    4. Linking to Sections within a Page

    The id attribute can be used to create anchor links within a page, allowing users to jump to specific sections.

    Example:

    Go to Section 2

    Section 2

    This is Section 2 of the document.

    <a href="#section2">Go to Section 2</a>
    <div style="height: 800px;"></div> <!-- Spacer for scrolling -->
    <h2 id="section2">Section 2</h2>
    <p>This is Section 2 of the document.</p>

    Conclusion

    The id attribute is a powerful tool in HTML that allows you to uniquely identify and style elements, manipulate them with JavaScript, and create internal links within your web pages.