1

I want to change the .innerHTML of every element with the class knopf_leer . I've tried using Ids document.getElementById("id").innerHTML = "replacement" and it works fine, so I'm quite surprised it doen't work with the class.

function ersetz_mich() {
  document.getElementsByClassName("knopf_leer").innerHTML = "replacement";
}
<a class="knopf_leer" onmouseover="ersetz_mich();">hi</a>
<a class="knopf_leer" onmouseover="ersetz_mich();">hi</a>
<a class="knopf_leer" onmouseover="ersetz_mich();">hi</a>
<a class="knopf_leer" onmouseover="ersetz_mich();">hi</a>

Help is very much appreciated!

sojutyp
  • 316
  • 1
  • 2
  • 11
  • Reading the [manual](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) is always helpful. – Teemu Feb 11 '18 at 11:14

1 Answers1

3

The method getElementsByClassName returns an HTMLCollection, not a single element. Therefore, you have to iterate over every element in it and set the innerHTML:

[].forEach.call(document.getElementsByClassName("knopf_leer"), function (element) {
    element.innerHTML = "replacement";
});

In your particular case, since you're making use of inline JavaScript, you can simply pass this as an argument and use that instead .

Snippet:

function ersetz_mich(element) {
  element.innerHTML = "replacement";
}
<a class="knopf_leer" onmouseover="ersetz_mich(this);">hi</a>
<a class="knopf_leer" onmouseover="ersetz_mich(this);">hi</a>
<a class="knopf_leer" onmouseover="ersetz_mich(this);">hi</a>
<a class="knopf_leer" onmouseover="ersetz_mich(this);">hi</a>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66