Learn Basic HTML Complete Course part 17

HTML Id Attribute


The id attribute refers to a unique value for an HTML element. This HTML id value can be used with CSS and JavaScript to perform certain task.


HTML id with CSS

In CSS, if you want to select an element with a specific id, write a hash (#) character, followed by the id of the element.


Syntex

<style>   
#myid {   
    background-color: lightpink;   
    color: black;   
    padding: 40px;   
    text-align: center;   
}    
</style>   
<h1 id="myid">Example of HTML id</h1>


📍Here the id attribute is "myid" which can be used on any HTML element. The HTML id value is case-sensitive and it must contain at least one character, and must not contain whitespace (spaces, tabs, etc.).


Difference between HTML Class and ID

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


Example

<!DOCTYPE html>   
<html>   
<head>   
<style>   
/* Style the element with the id "myid"  This tutorial is provided By topblogpk.blogspot.com*/   
#myid {   
background-color: pink;   
color: black;   
padding: 40px;   
text-align: center;   
}   

/* Style all elements with the class name "fruit" */   
.fruit {   
background-color: orange;   
color: white;   
padding: 10px;   
}    
</style>   
</head>  

<body>   

<h2>Difference Between Class and ID</h2>   

<h1 id="myid">My Favorite Fruits</h1>   

<h2 class="fruit">Mango</h2>   
<p>The Kinkg of all fruits.</p>   

<h2 class="fruit">Orange</h2>   
<p>Full of Vitamin C</p>   

<h2 class="fruit">Apple</h2>   
<p>An apple a day, keeps the doctor away.</p>   

</body>   
</html>

output:

Difference Between Class and ID

My Favorite Fruits

Mango

The Kinkg of all fruits.

Orange

Full of Vitamin C

Apple

An apple a day, keeps the doctor away.



HTML id with JavaScript

<!DOCTYPE html>
<html>
<body>
<h2>HTML id with JavaScript</h2>
<h1 id="hello">Hello Friends on TopBlog Pk!!!</h1>
<button onclick="displayResult()">Change text</button>
<script>
function displayResult() {
document.getElementById("hello").innerHTML = "All the best for future By TopBlog Pk!";
}
</script>
</body>
</html>

output:


HTML id with JavaScript

All the best for future By TopBlog Pk!


Or
Click Here On Change text Button
📍



Post a Comment

© Top Blog Pk. All rights reserved. Developed by Jago Desain