Using The class Attribute
The class attribute specifies one or more class names for an HTML element.
The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name.
Example
Using CSS to style all elements with the class name "city":
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;} </style>
<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>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Try it Yourself »
Using CSS to style all elements with the class name "city":
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;} </style>
<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>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Try it Yourself »London
London is the capital of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
The class attribute can be used on any HTML element.
The class attribute can be used on any HTML element.
Using The class Attribute in JavaScript
JavaScript can access elements with a specified class name by using the getElementsByClassName() method:
Example
When a user clicks on a button, hide all elements with the class name "city":
<script>
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}</script>
Try it Yourself »
When a user clicks on a button, hide all elements with the class name "city":
<script>
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}</script>
Try it Yourself »Multiple Classes
HTML elements can have more than one class name, each class name must be separated by a space.
Example
Style elements with the class name "city", also style elements with the class name "main":
<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
Try it Yourself »
In the example above, the first h2 element belongs to both the "city" class and the "main" class.
Style elements with the class name "city", also style elements with the class name "main":
<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
Try it Yourself »Same Class, Different Tag
Different tags, like <h2> and <p>, can have the same class name and thereby share the same style:
Example
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>
Try it Yourself »
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>
Try it Yourself »
No comments:
Post a Comment