Login With Github

HTML Id

The id attribute defines the unique identifier of the HTML element. The id must be unique in the HTML document.

In CSS, use “#id” command to select the HTML element and define the style for it.

In JavaScript, you can call the document.getElementById(id) method to find HTML elements.

Id Attribute Syntax

Every html element can define an id attribute.In the following example, we define the id attribute for the <h1> element and define CSS styles for it:

<style>
#articleTitle {
    background-color: lightblue;
    color: black;
    padding: 40px;
    text-align: center;
}
</style>

<h1 id="articleTitle">My First Article</h1>

Note: The id attribute value is case-sensitive.

The id attribute value cannot have spaces and cannot begin with a number.

Difference between id attribute and class attribute

The id of each element in the HTML document must be unique.However, multiple HTML elements can define the same class attribute, for example:

<style>
/* Style the element with the id "myHeader" */
#myHeader {
    background-color: lightblue;
    color: black;
    padding: 40px;
    text-align: center;
}

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

<!-- A unique element -->
<h1 id="myHeader">My Cities</h1>

<!-- Multiple similar elements -->
<h2 class="city">London</h2>
<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

Finding HTML elements with id in JavaScript

Here is an example of changing the text content for the element whose id value is myHeader:

<script>
function displayResult() {
    document.getElementById("myHeader").innerHTML = "HTML is so easy!";
}
</script>

0 Comment

temp