HTML Global id Attribute

❮ Previous Global Attributes Next ❯


<!DOCTYPE html>

<p id="myDemo">Hello World!</p>
<button onclick="myFunction()">Change text color</button>

function myFunction() {
  document.getElementById("myDemo").style.color = "red";



The id attribute specifies a unique alphanumeric identifier to be associated with an element.

Accessing naming an element is important to being able to access it with a style sheet, a link, or a scripting language.

Name should be unique to a document and should be meaningful for example; although id="x1" is perfectly valid, id="Paragraph1" might be better.

Values for the id attributemust begin with a letter (A–Z or a–z) and may be followed by any number of letters, digits, hyphens, or periods.

Practically , a period character should not be used within an id value given the use of these values in scripting languages and possible confusion with class names.

Once elements are named with id, they should be easy to manipulate with a scripting language. Commonly they are referenced using the DOM method getElementById().

As same as the class attribute, the id attribute is also used by style sheets for accessing a particular element. For example, #Paragraph1 {color: red;}

Once an element is named using id, it also is a potential destination for an anchor, for example:

<a href="#main">Go to main</a>
<div id="main">This is the main of the page.</div>

The main problem with the id attribute is that, for some elements, particularly <form> controls and images, the <name> attribute already serves its function. You should be careful when using both <name> and id together, especially when using older element syntax with newer styles.

Standard Syntax

<element id="id">

Browser Support


Attribute Values

Value Description
id Identifiers must be at least one character long and should not present space characters.
❮ Previous Global Attributes Next ❯