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!
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments