HTML Classes



The HTML class attribute is used to specify a single or multiple class names for an HTML element.

Using The class Attribute

The class name can be used by CSS and JavaScript to do some tasks for HTML elements.

You can use this class in CSS with a specific class, write a period (.) character, followed by the name of the class for selecting elements.

A class attribute can be defined within <style> tag or in separate file using the (.) character.

In an HTML document, we can use the same class attribute name with different elements.


Example :

<!DOCTYPE html>
<html>
  <head>
    <style>
      .headings {
        color: rgb(251, 255, 0);
        font-family:'Arial';
        background-color: rgb(110, 0, 0);
      }
    </style>
  </head>
  <body>
    <h1 class="headings">This is first heading</h1>
    <h2 class="headings">This is Second heading</h2>
    <h3 class="headings">This is third heading</h3>
    <h4 class="headings">This is fourth heading</h4>
  </body>
</html>

Output :  


You can use class attribute on any HTML element. The class name is case-sensitive.


Example :

<!DOCTYPE html>
<html>
  <style>
    .fruit {
      background-color: orange;
      color: white;
      padding: 10px;
    }

    .center {
      text-align: center;
    }
  </style>

  <body>
    <h2>Multiple Classes</h2>
    <p>
      All three elements have the class name "fruit". In addition, Mango also has the class name "center", which center-aligns the text.
    </p>

    <h2 class="fruit center">Mango</h2>
    <h2 class="fruit">Orange</h2>
    <h2 class="fruit">Apple</h2>
  </body>
</html>

Output :


Different Elements Can Share Same Class

Different HTML elements can point to the same class name.


Example :

<h2 class="city">New Delhi</h2>
<p class="city">New Delhi is the capital of India</p>

Class Attribute in JavaScript

You can use JavaScript access elements with a specified class name by using the getElementsByClassName() method.


Example :

<!DOCTYPE html>
<html>
  <body>
    <h2>Class Attribute with JavaScript</h2>
    <p>Click the button, to hide all elements with the class name "fruit", with JavaScript:</p>

    <button onclick="myFunction()">Hide elements</button>

    <h2 class="fruit">Mango</h2>
    <p>Mango is king of all fruits.</p>

    <h2 class="fruit">Orange</h2>
    <p>Oranges are full of Vitamin C.</p>

    <h2 class="fruit">Apple</h2>
    <p>An apple a day, keeps the Doctor away.</p>

    <script>
      function myFunction() {
        var x = document.getElementsByClassName("fruit");
        for (var i = 0; i < x.length; i++) {
          x[i].style.display = "none";
        }
      }
    </script>
  </body>
</html>

Output :

After Click on Button :