HTML Class Attribute

In this tutorial, you will learn HTML Class Attribute. The HTML classes are used to identify various elements in your web documents. HTML Classes allows you to reference the element when you need to put some style to the elements. The class is a global attribute is a space-separated list of the case-sensitive class element. So, let’s take a look at an example:

<style>
.classname {
  background-color: purple;
  color: white;
  margin: 20px;
  padding: 20px;
} </style>
<div class="classname">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div class="classname">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>

Although, the specification does not add requirements on the name of a class. Many programmers are encouraged to use the names which define the semantic purpose of the element. The HTML class Attribute uses the class attributes to build their web page in a modern style using a cascading style sheet (CSS).

HTML Class Attribute

Specific Class Attribute

In (CSS) select an element with a specific class attribute, write a period(.), character, followed by the name of the class. So, let’s take a look at an example:

<style>
.city {
  background-color: orange;
  color: black;
  padding: 10px;
}
</style>
<p>Use CSS to style elements with the class name "city":</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

Multiple Classes

The HTML elements can be set multiple classes by listing the classes in the class attribute within the element or outside the element. If the HTML multiple classes attribute names the same then it will style for all of them will be the same. But if you need to style them separately then you need to assign a class attribute. The class attributes should differ from each other. So, let’s take a look at the example:

<style>
.city {
  background-color: orange;
  color: black;
  padding: 10px;
} 
.main {
  text-align: center;
}
</style>
<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>

Class Attribute in JavaScript

The class Attribute in JavaScript name can be used within JavaScript to perform a particular task for elements with the specific class name. javaScript can access elements with class name by using javascript method getElementByClassName(). So, let’s take a look at HTML attribute the example:

<button onclick="myFunction()">Hide elements</button>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<script>
function myFunction() {
  var x = document.getElementsByClassName("city");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *