Various HTML elements can reference the same class name.
In the provided example, both <h2> and <p> elements are associated with the “city” class, thus inheriting the same style.
Example
<h2 class=”city”>Paris</h2> <p class=”city”>Paris is the capital of France</p> |
JavaScript can utilize the class name to execute specific tasks on particular elements.
Elements with a specific class name can be accessed by JavaScript using the getElementsByClassName() method.
Example
Click a button to conceal all elements having 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> |