In the previous article, Mytour introduced you to HTML block elements. In this subsequent piece, Mytour will continue the discussion, focusing on the class attribute in HTML.
HTML Class Attribute
1. HTML Class Attribute
2. Using the Class Attribute for Inline Elements
2.1. Selecting Elements with Specific Classes
2.2. HTML Elements Can Have Multiple Classes
2.3. Different Tags Sharing the Same Class
3. Using the Class Attribute in JavaScript
1. HTML Class Attribute
As mentioned earlier, the HTML class attribute is used to specify one or multiple class names for HTML elements.
This attribute can be used on any HTML element. CSS and JavaScript use class names to perform specific tasks for elements with specified class names.
The outcome after applying the HTML class attribute is formatted as follows:
2. Using the Class Attribute for Inline Elements
The HTML class attribute is also applied to inline elements.
Example: In the following example, we apply the class attribute to an inline element:
The resulting output after applying the HTML class attribute to the inline element looks like this:
Note:
- The class attribute can be used on any HTML element.
- Class names must be written in uppercase.
2.1 Selecting Elements with Specific Class
In CSS, we can select elements with a specific class by adding a dot (.) followed by the class name.
Example: Below is an illustration of selecting elements with a specific class:
The resulting output looks like this:
2.2. HTML Elements Can Have Multiple Classes
HTML elements can contain one or multiple class names, each separated by a space.
Example: The following example illustrates an HTML element with multiple classes:
The resulting output looks like this:
In the example above, the first h2 element belongs to both the 'city' and 'main' classes.
2.3. Different Tags Can Share the Same Class
Different tags like h2 and p can have the same class name, allowing them to share the same style.
Example: The following example illustrates different tags sharing the same class:
The resulting output looks like this:
3. Using the Class Attribute in JavaScript
JavaScript utilizes class names to execute specific tasks for elements with designated class names.
JavaScript can access elements with specified class names using the getElementsByClassName() method.
Example: The following example illustrates how to use the class attribute in JavaScript:
The resulting output looks like this:
In this article, Mytour has introduced you to the class attribute in HTML. In the next article, Mytour will further introduce you to the id attribute in HTML. If you have any questions or concerns, feel free to leave your comments below the article for Mytour to address and assist you in improving your HTML skills.