class Attribute
Description
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.
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>
You can apply multiple classes to each element by separating the class names with a space.
Example 2
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 ww w . j a v a2s .c o m-->
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>
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";
}<!-- ww w . ja va 2s . c om-->
</script>
</body>
</html>
The above script finds all of the elements
that have been assigned to the otherclass
class and applies some styling.