Home » Web programming/HTML

HTML The id Attribute

The id attribute is used to define unique id for an element in HTML. In this tutorial on id attribute, we will learn about the HTML id attribute with a few examples.
Submitted by Shivang Yadav, on December 15, 2019

The id attribute is used to specify a unique id for an element in HTML. This id cannot be used for multiple elements in HTML. You can add the id to any HTML element.

The naming id attributes The id name is case-sensitive, the name must have one character and no whitespaces in two words (spaces, tabs, etc).

Using id attribute

The id attribute can be used to reference the HTML tag in CSS and JavaScript to perform a certain transformation in an HTML tag that contains the id attribute. We use # followed by the name of the id attribute to refer to the element.

Referencing id Attribute in CSS

<!DOCTYPE html>


        #element {
            background-color: #f40;
            color: #fff;
            padding: 40px;
            text-align: center;


    <h1 id="element">Hello! This is an HTML element. </h1>




HTML The id attribute | Example 1

Referencing id attribute in JavaScript

In JavaScript also, we can use the id attribute to reference an element and perform a specific task on it. document.getElementById() is used to reference an element using JavaScript.

<!DOCTYPE html>


    <h1 id="greeting">Welcome Text</h1>
    <button onclick="displayResult()">Say Hello!</button>
        function displayResult() {
            document.getElementById("greeting").innerHTML = "Hello! ";




HTML The id attribute | Example 2

After clicking on the "Say Hello!" button...

HTML The id attribute | Example 3

Uses of id in Webpage

ids of elements along with links are a great way for navigation to element on the same page which is so long.

Using the link to a specific id in the page will navigate us to that element in HTML.

We will see a separate example to do this.

Classes vs ID Attribute in HTML

In HTML, two elements are used to reference the HTML element. A class can be used to reference multiple HTML elements whereas id can be used to reference single HTML elements.

Read: Class attribute in HTML

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.