Categories
Web development

HTML id Attribute

Learn how to use the HTML id Attribute.



HTML id Attribute

The HTML id attribute is used to define a special id for an HTML element.

The value of the HTML id attribute needs to be unique within the HTML document (you cannot have more than one element with the same id in an HTML document).

Syntax:

<element id="idname"> 

idname – defines a unique id for the element (should contain at least one character, shouldn’t contain any space characters).

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#example {
  background-color: #0a9396;
  color: white;
  padding: 40px;
  text-align: center;
} 
</style>
</head>
<body>

<p id="example">This is a paragraph.</p>

</body>
</html>

Output:

This is a paragraph.

The HTML id attribute you can use also in JavaScript to perform some tasks for the desired element.

Example:

Access an element with a specific id with the getElementById() method:

<!DOCTYPE html>
<html>
<body>

<p id="example-2">Hello!</p>
<button onclick="changeText()">Click here</button>

<script>
function changeText() {
  document.getElementById("example-2").innerHTML = "Have a nice day!";
}
</script>

</body>
</html>

Output:

Click on the button to change the text:

Hello!


Enjoy coding!

Read also:

HTML class Attribute

HTML Scroll Box

HTML Table