HTML Classes

In HTML, classes are used to apply CSS styles or JavaScript functionality to one or more elements. Classes allow you to group multiple elements together and target them collectively for styling or scripting purposes. By assigning the same class to multiple elements, you can easily apply consistent styles or behavior to those elements. Here's how you can use classes in HTML:


1. Defining a class:

To define a class, you use the `class` attribute on an HTML element and assign it a name. The class name should be meaningful and descriptive. You can apply the same class name to multiple elements to group them together.

html
<p class="highlight">This paragraph has a class of "highlight".</p>
<div class="highlight">This div also has a class of "highlight".</div>

2. Applying styles with CSS:

Once you have assigned a class to an element, you can use CSS to target and style elements with that class. To select elements based on their class, you use the dot (`.`) notation followed by the class name in your CSS rules.

css
.highlight {
    color: red;
    font-weight: bold;
}

In the above example, any element with the class "highlight" will have red text color and bold font weight.


3. Targeting elements with JavaScript:

Classes are also commonly used in JavaScript to target elements for manipulation or interaction. You can use JavaScript methods like `querySelector()` or `getElementsByClassName()` to select and manipulate elements based on their class.

javascript
var elements = document.getElementsByClassName("highlight");
for (var i = 0; i < elements.length; i++) {
    elements[i].textContent = "Changed!";
}

The JavaScript code above selects all elements with the class "highlight" and changes their content to "Changed!".


By using classes, you can efficiently apply styles or functionality to multiple elements throughout your HTML document, making it easier to maintain and update your code.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext