Skip to main content

Classes in HTML

The class attribute in HTML is used to define one or more classes for an HTML element.

Classes are essentially a way of grouping elements together based on a shared set of characteristics or styles.

The class attribute is commonly used in conjunction with CSS styles, which allow developers to apply styles to elements based on their class.

As an example:

Editor

Loading...

Syntax For Class

The syntax for adding a class attribute to an HTML element is very simple.

To add a class to an element, you simply need to include the class attribute and specify the name of the class or classes that you want to apply.

Here's the syntax for adding a class to an HTML element:

<element class="class-name"></element>

Explanation:

  • The element is the HTML element that you want to add the class attribute to, and class-name is the name of the class that you want to apply.

Multiple Classes

If you want to apply multiple classes to an element, you can simply separate the class names with a space.

As an example:

<element class="class-name1 class-name2"></element>

Explanation:,

  • both class-name1 and class-name2 will be applied to the element.
descriptive class names

The name of a class can be anything you want, as long as it doesn't contain spaces or other special characters. It's common to use descriptive class names that describe the purpose or style of the element that the class is being applied to.

Different Elements Can Share Same Class

It's common practice to use the same class for multiple elements throughout a website to apply consistent styles to those elements.

As an example:

Editor

Loading...

In this example:

  • The class "heading-font" is defined in the CSS file with a particular font-family, size, weight, and color.
  • Then, that class is applied to all of the heading elements on the website, including <h1>, <h2>, <h3>, and so on.

The class Attribute in JavaScript

The class attribute can also be used in JavaScript to manipulate HTML elements.

You can select HTML elements based on their class using the getElementsByClassName() method or the querySelectorAll() method.

As an example:

Editor

Loading...

In this example:

  • We have added a button to the HTML page that calls a JavaScript function when it is clicked.
  • The function selects all elements with the class "blue" using the getElementsByClassName() method, and then loops through each element and changes its backgroundColor property to "lightblue".