HTML - class Attribute



HTML class attribute is used to give an HTML element a class, multiple classes can be specified on a single element. By utilizing that class attribute to select an element through CSS and JavaScript, we can style or alter that element.

Syntax

   <tag class="classname"></tag>

Attribute Values

  • classname: The classname could be anything you like to use to select that element.

Try to click the icon run button run button to run the following HTML code to see the output.

Examples of HTML class Attribute

Using class attribute to set background color

In this example we will use class attribute, and use that class name in css to select that element and set the background color to green and padding 5px.

<!DOCTYPE html>
<html>
<head>
   <style>
    /* Class Selector Used to Select the Element */
   .highlight {
       background-color: green;
       padding: 5px;
   }
   </style>
</head>
<body>
    <!-- HTML Class attribute used on p Element -->
   <p class="highlight">This is a highlighted paragraph.</p>
</body>
</html>   

Using class attribute to set the hover effect

In this example we will use the class attribute, and use that class name in CSS to select that element and set a hover effect on the selected element.

<!DOCTYPE html>
<html>
<head>
    <style>
        /* Class Selector Used to Select the Element */
        .highlight:hover {
            background-color: green;
            padding: 5px;
        }
    </style>
</head>
<body>
    <!-- HTML Class attribute used on p Element -->
    <p class="highlight">This is a highlighted paragraph.</p>
</body>
</html>

Using class attribute to set background color in JavaScript

In this example we will use the class attribute, and use that class name in JavaScript to select that element and set the background color to green and padding 5px.

<!DOCTYPE html>
<html>
   <head>
      <script>
         /* Class Selector Used to Select the Element */
         function myFunction() {
         let x = document.getElementsByClassName("highlight");
         x[0].style.backgroundColor = "green";
         x[0].style.padding = "5px";
         }
      </script>
   </head>
   <body>
      <!-- HTML Class attribute used on p Element -->
      <p class="highlight">This is a highlighted paragraph.</p>
      <button onclick="myFunction()">Highlight</button>
   </body>
</html>   

Supported Browsers

Attribute Chrome Edge Firefox Safari Opera
class Yes Yes Yes Yes Yes
Advertisements