There is an elements
object, which is not Array but array-like HTML object.
I need to alert
innerHTML
of each element
in 1 second after click
on it.
I wrote this code (below), but it doesn't work.
[].forEach.call(elements, function (element) {
element.onclick = () => setTimeout(alert(element.innerHTML), 1000);
});
I intuitively know that there is an error in this code (even without its execution), but I don't know where and what is it like (something wrong with arguments maybe?).
Use of forEach
is mandatory (indexer i
is used in original code).
Perhaps omitting insignificant details of the problem, I missed something meaningful. So I bring a more complete piece of code:
var colors = ["red", "green", "blue"];
var fragment = document.createDocumentFragment();
colors.forEach(function (color, i) {
var span = document.createElement("SPAN");
span.style.backgroundColor = color;
span.tabIndex = i + 1;
span.onclick = () => setTimeout(console.log(span.innerHTML), 1000);
fragment.appendChild(span);
});