HTML Java

HTML Id


HTML The id Attribute

  • The id attribute is a unique identifier which is used to specify the document.
  • It is used by CSS and JavaScript to perform a certain task for a unique element.
  • In CSS, the id attribute is used using # symbol followed by id.

Example

<html>
<head>
<style>
  #myHeader {
   background-color: tomato;
   color: black;
   padding: 40px;
   text-align: center;
}
</style>
</head>
<body>
  <h2>The id Attribute</h2>
  <p>Use CSS to style an element with the id "myHeader":</p>
</body>
</html>
Try it »

Note:- The id value is case-sensitive.

The id value must contain at least one character, and must not contain whitespace (spaces, tabs, etc.).



Difference Between Class and ID

An HTML element can only have one unique id that belongs to that single element, while a class name can be used by multiple elements.

Example

<html>
<head>
<style>
  #myHeader {
   background-color: lightblue;
   color: black;
   padding: 40px;
   text-align: center;
}
</style>
</head>
<body>
  <h2>Difference Between Class and ID</h2>
  <p>An HTML page can only have one unique id applied to one specific element, while a class name can be applied to multiple elements.</p>
</body>
</html>
Try it »


Bookmarks with ID and Links

  • HTML bookmarks are used to allow readers to jump to specific parts of a Web page.
  • Bookmarks can be useful if your webpage is very long.
  • To make a bookmark, you must first create the bookmark, and then add a link to it.
  • When the link is clicked, the page will scroll to the location with the bookmark.


Using The id Attribute in JavaScript

JavaScript can access an element with a specified id by using the getElementById() method:

Example

<html>
<body>
  <h1 id="myHeader">Difference Between Class and ID</h1>
  <button onclick="displayResult()">Change Text</button>
</body>
</html>
Try it »