How to specify a unique id for an element in HTML?


For each HTML element, the id attribute specifies a special id. The id attribute's value must be distinct across the HTML content. A specific style declaration in a style sheet is referenced using the id attribute. JavaScript also uses it to access and modify the element with the given id.

Following are the examples…

Example

In the following example we are using <h1> pointing to id name ”tutorial”. This <h1> will get styled according to the #tutorial.

<!DOCTYPE html> <html> <head> <style> #tutorial { background-color: lightblue; color: black; padding: 40px; text-align: center; } </style> </head> <body> <h1 id="tutorial">Welcome Everyone..</h1> </body> </html>

Output

On executing the above script, the element with id "tutorial" will get styled according to the #tutorial.

Example: Using Javascript

Javascript uses the unique id and manipulates the element with given id.

<!DOCTYPE HTML> <html> <body> <h1 id="tutorial">Hello</h1> <button onclick="displayResult()">change text</button> <script> function displayResult() { document.getElementById("tutorial").innerHTML = "WELCOME"; } </script> </body> </html>

Output

When you try to execute the script at first, it will display the text "hello".

On clicking the change text button, the text "hello" will be changed to "welcome".

Updated on: 05-Sep-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements