Ep. 009 – Class and ID Attributes – Learn HTML and HTML5

In the previous post, we have learned how to use the style tag, link tag, and script tag. In this post, we will learn how and why we use the class attribute and id attribute?

Class Attribute:

The class attribute is mainly used to style HTML tags/elements. Let’s say that we have four paragraphs <p> on our HTML page and we want to change the color of the two paragraph elements to red. The answer is the class attribute. We will add a class attribute to those two paragraphs for which we want to change the text color to red. Then we will assign the color value red to the assigned class. We use the dot (.) to access the class attribute in the CSS code. See the following code example:

Code:

<style>
    .redparagraph {
        color: red;
    }
</style>
<p>Paragraph 1</p>
<p class="redparagraph">Paragraph 2</p>
<p class="redparagraph">Paragraph 3</p>
<p>Paragraph 4</p>

Output:

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

The advantage of using the class attribute is that we do not need to repeat our CSS styles for each element. Rather than repeating the styles for each and every element, we assign the class attributes to the elements sharing the same CSS styles as shown in the above example.

ID Attribute:

The id attribute can be added in any HTML element/tag and is mainly used to access the element inside the JavaScript code. While adding the id attribute to any HTML element, make sure that the id attribute is unique and is never used on any other HTML element/tag on that page. The following example shows how can access an element by using its id attribute and then apply CSS style using JavaScript code:

Code:

<p>Paragraph 1</p>
<p id="blueparagraph">Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>

<script>
document.getElementById('blueparagraph').style.color = 'blue';
</script>

Output:

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

In the above example, we have changed the color of a paragraph element by accessing it through its id attribute using JavaScript code. Don’t worry if you couldn’t understand the JavaScript code, we will discuss it in the JavaScript course.

Video Tutorial (Urdu Language):

The Class and ID Attributes

Got Stuck? Any Questions?

In case of any questions, please feel free to ask in the comments section below. Thanks

Leave a Comment

Your email address will not be published.