0

I started to learn JavaScript today. Sorry for easy question.

I don't understand the logic of getElementsByClassName. Here is my example code, I want to change onclick the the second content but when I click the button nothing is change.

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p class="demo">JavaScript can change HTML content.</p>
<p class="demo">This is the second content which I want to change.</p>

<button type="button" onclick='document.getElementsByClassName("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>
piseynir
  • 237
  • 1
  • 4
  • 14
  • 1
    For starters: stop using inline `on*` handlers. JS should be in one place only, and that's its respective tag or file. Use [Element.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) instead. – Roko C. Buljan Feb 26 '22 at 11:14
  • 1
    `.getElementsByClassName("demo")` is a **collection of elements**. Not a single one on which you could do `.innerHTML` Read more here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – Roko C. Buljan Feb 26 '22 at 11:16
  • Thanks for reply. I don't understand the first but understand the second. – piseynir Feb 26 '22 at 11:19
  • Simple. Stop using `onclick` as a HTML attribute. Instead create a ``. Inside your script use then addEventListener. – Roko C. Buljan Feb 26 '22 at 11:24

0 Answers0