HTML Class Attribute

Used to apply internal or external css styles to an element with a class name.
This style will be applied for multiple elements.
The class can be identified in css as .name
The class name in class attribute is also used in js to change or add the styles or classnames.
The class attribute takes a class names, which consits a set of styles, The class name is kept in the attribute and many class names can be kept seperated by a space.
Syntax: <tagname class="classname1 classname2" > Content <tagname>

Example

<!DOCTYPE html>
<html>
<head>
<style>
.topic {
    background-color: red;
    font-size:25px; 
}
</style>
</head>
<body>

<h1 class="topic">Heading</h1>
<p>This is a <span class="topic">Paragraph</span>.</p>

</body>
</html>

Multiple Classes

You can add Multiple class to a single element.
You can also add the same class many times to other elements.

Example

<!DOCTYPE html>
<html>
<head>
<style>
.highlighted {
  background-color: yellow;
  color: black;
}

.large-font {
  font-size: 24px;
}
</style>
</head>
<body>

<p class="highlighted large-font">This paragraph has two classes: "highlighted" and "large-font".</p>
<p class="highlighted">This paragraph has one with highlighted class used second time.</p>
<p class="large-font">This paragraph has one with large-font class used second time.</p>
<div class="highlighted large-font">This div element has two classes: "highlighted" and "large-font".</div>
</body>
</html>

Class name used in Javascript

When it comes to JavaScript, you can use the class attribute to select and manipulate elements with a specific class name using JavaScript functions like querySelector() or getElementsByClassName().
This allows you to add or remove classes dynamically, which can be helpful for creating interactive webpages.

Example

<!DOCTYPE html>
<html>
<head>
<style>
.highlighted {
  background-color: yellow;
  color: black;
}

.large-font {
  font-size: 24px;
}
</style>
</head>
<body>

<p class="clickable" onclick="highlight(this)">Click me to highlight!</p>

<script>
  function highlight(element) {
    element.classList.add("highlighted");
  }
</script>
</body>
</html>

Explanation: In this example, when the user clicks on the paragraph, the highlight() function is called, and it adds the "highlighted" class to the paragraph, which would apply the CSS styles defined for the .highlighted class.

Quick Recap - Topics Covered

HTML Class
Multiple Classes
Class in javascript

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compile or Try on own Now

Example js

Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK

Rating


Message