0

I'm going to put this JavaScript code in the <button onclick"">

I don't understand why it does not work

if possible, please modify the code

<button onclick='document.getElementsByClassName("city");for (var i = 0; i < x.length; i++) {x[i].style.display = "none";}'>Hide 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>
  • You've never defined `x`. – Teemu Aug 01 '20 at 08:08
  • You never define `x` and you never do anything with the result of `document.getElementsByClassName("city")`. A variable _assignment_ could help here, but please consider another approach. Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_—_dont_use_these) instead. – Sebastian Simon Aug 01 '20 at 08:10
  • 1
    So, try `Array.from(document.getElementsByClassName("city")).forEach(({style}) => style.display = "none");` instead. See [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from), [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). Consider [using CSS classes](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) instead of setting `style`s directly. – Sebastian Simon Aug 01 '20 at 08:15

0 Answers0