HTML global attribute class








The class attribute sets the class. We usually use class to group elements.

Then we can locate elements that belong to a given class and apply a CSS style.

Syntax

<element class="classname">

Attribute Values

classname
one or more class names for an element.

Browser compatibility

class Yes Yes Yes Yes Yes




Example

<!DOCTYPE HTML>
<html>
    <body>
        <a class="class1  class2" href="http://apress.com">Apress web site</a>
        <p/>
        <a class="class2 otherclass" href="http://w3c.org">W3C web site</a>
    </body>
</html>





Example 2

You can apply multiple classes to each element by separating the class names with a space.

In the following code we create a style targeting one of more of the classes.

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.class2  {<!--from w w  w .  j av  a 2s  . com-->
   background-color:grey; color:white; padding:5px; margin:2px;
}
.class1  {
   font-size:x-large;
}
</style>
</head>
<body>
    <a class="class1  class2" href="http://java2s.com">web site</a>
    <p/>
    <a class="class2 otherclass" href="http://w3c.org">W3C web site</a>
</body>
</html>

Click to view the demo

Example 3

Another way to use the class attribute is in a script.

<!DOCTYPE HTML>
<html>
<body>
<a class="class1  class2" href="http://java2s.com">web site</a>
<br/>
<a class="class2 otherclass" href="http://w3c.org">W3C web site</a>
<script type="text/javascript">
var  elems  = document.getElementsByClassName("otherclass");
for (i = 0; i < elems.length; i++)   {
   var  x  = elems[i];
   x.style.border = "thin solid black"; 
   x.style.backgroundColor = "white"; 
   x.style.color = "black";
}<!--from w  w w .j  a v  a 2  s.  co m-->
</script>
</body>
</html>

Click to view the demo

The above script finds all of the elements that have been assigned to the otherclass class and applies some styling.