Hide elements onclick - getElementsByClassName("")

PHOTO EMBED

Fri Aug 12 2022 11:41:18 GMT+0000 (Coordinated Universal Time)

Saved by @fastoch #html #javascript

<!DOCTYPE html>
<html>
<body>

<h2>Use of The class Attribute in JavaScript</h2>
<p>Click the button to hide all elements with class name "city":</p>
<button onclick="myFunction()">Hide elements</button>

<p>Click the button to show all elements with class name "city":</p>
<button onclick="myFunction2()">Show 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>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

<script>
function myFunction() {
  var x = document.getElementsByClassName("city");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
}

function myFunction2() {
  var x = document.getElementsByClassName("city");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "block";
  }
}
</script>

</body>
</html>
content_copyCOPY

https://www.w3schools.com/html/html_classes.asp