DEV Community

wasifali
wasifali

Posted on • Updated on

HTML classes and HTML class attribute

HTML class Attribute

The HTML class attribute is used to specify a class for an HTML element.
The class attribute is often used to point to a class name in a style sheet.
we have three <div> elements with a class attribute with the value of "city". All of the three <div> elements will be styled equally according to the. city
we have two <span> elements with a class attribute with the value of "note".
Both <span> elements will be styled equally according to the. note style

<!DOCTYPE html>
<html>
<head>
<style>
.city {
  background-color: tomato;
  color: white;
  border: 2px solid black;
  margin: 20px;
  padding: 20px;
}
</style>
</head>
<body>

<div class="city">
  <h2>London</h2>
  <p>London is the capital of England.</p>
</div>

<div class="city">
  <h2>Paris</h2>
  <p>Paris is the capital of France.</p>
</div>

<div class="city">
  <h2>Tokyo</h2>
  <p>Tokyo is the capital of Japan.</p>
</div>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Syntax:

write a period (.) character, followed by a class name. Then, define the CSS properties within curly braces {} to create a class.

<!DOCTYPE html> 
<html>
 <head> 
<title>
Example
</title>
 <style>
 . myClass
 {
 color: blue; font-size: 20px;
 }
 </style>
 </head>
 <body>
 <p class="myClass">This is a paragraph with the class "myClass”. </p> 
</body>
 </html>
Enter fullscreen mode Exit fullscreen mode

Multiple Classes

HTML elements can belong to more than one class.
<h2> element belongs to both the city class and also to the main class

Example

<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
Enter fullscreen mode Exit fullscreen mode

Different Elements Can Share Same Class

Different HTML elements can point to the same class name.
both <h2> and <p> point to the "city" class and will share the same style:

Example

HTML
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>
Enter fullscreen mode Exit fullscreen mode

Use of The class Attribute in JavaScript

JavaScript can access elements with a specific class name with the getElementsByClassName() method

<script>
function myFunction() {
  var x = document.getElementsByClassName("city");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)