How To Use HTML Id Attribute In HTML Page

HTML Id Attribute

HTML id attribute specifies unique element within HTML document.Keep in mind that,same id attribute of HTML element can not assign to other HTML element.

Note HTML id attribute specifies unique HTML element means no other HTML element can put same id.

HTML Id Attribute

General Syntax

<h3 id="main_heading">Heading tag having id attribute.</h3>    

Source Code

Download
<h3 id="main_heading">HTML heading element having id attribute.</h3>

Source Code : Output

HTML heading element having id attribute.

Code Explanation

Note:Here,HTML element <h2> having unique id(main_heading). That will be unique inside the HTML document.

Writing CSS Style To HTML Id Element

To write a cascade style sheet for the specific Id of the HTML element, write a hash character followed by an id name. Then define the CSS rule inside curly bracket{}.

Example

General Syntax

<style type="text/css">
#main_heading { 
background-color:orange;
color: black;
padding: 40px;
text-align: center; 
}
</style>    

Source Code

Download
<style type="text/css">
#main_heading {
background-color:orange;
color: black; 
padding: 40px; 
text-align: center;
}
</style>

Source Code : Output

Code Explanation

Note: The CSS rule has been written with respect to the unique id of the HTML element is only applicable to a single HTML element.

Javascript:Fetching HTML Element Through Id

Example

General Syntax

<script type="text/javascript">
function displayResult() {
 document.getElementById("main_heading").innerHTML = "You can see the result right now.";
}
</script>    

Source Code

Download
<script type="text/javascript">
 function displayResult() {
  document.getElementById("main_heading").innerHTML = "You can see the result right now.";
 }
</script>

Source Code : Output

Code Explanation

Note:Javascript is used getElementById() method to fetch HTML element having a unique id.

Difference Between Id And Class

General Syntax

<style type="text/css">
/* Style the element with the id "myHeader" */
#main_heading{
}
/* Style all elements with the class name "city" */
.flower{
}
</style>    

Source Code

Download
<style type="text/css">
/* Style the element with the id "myHeader" */
#main_heading{
  background-color: violet;
  padding: 20px;
  text-align: center;
  color: black;
}
/* Style all elements with the class name "city" */
.flower{
  background-color: orange;
  padding: 12px;
  color: black;
}
</style>

Source Code : Output

Code Explanation

Note:An HTML element has a unique id means this id can not assign to other HTML elements while a class to be assigned more than one HTML element.

Online Test / Quiz

Our Tutorials

Html Tutorial HTML
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4
Materialize CSS Tutorial MATERIALIZE CSS
2021-22 © shapeyourpath.com