"Cannot read property 'style' of undefined"
The reason you're seeing this error is because the for
loop has already ended and i
is outside of the bounds of the inputs
NodeList when the click
event is fired. In other words, since the last element's index in the array is one less than the length, inputs[i]
is undefined since i
is equal to the length of the NodeList when the click
event listener is fired.
To work around this, you could change inputs[i]
to this
in order to access the clicked element. In doing so, you avoid having to use i
(which is what was causing the problem):
var inputs = document.querySelectorAll("input[type=text]")
for (i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('click', function() {
this.style.width = "500px";
});
}
Alternatively, you could use an IIFE in order to pass the value of i
on each iteration:
var inputs = document.querySelectorAll("input[type=text]")
for (i = 0; i < inputs.length; i++) {
(function(i) {
inputs[i].addEventListener('click', function() {
inputs[i].style.width = "500px";
});
})(i);
}
You could also use the .bind()
method to pass the value of i
:
var inputs = document.querySelectorAll("input[type=text]")
for (i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('click', function(i) {
inputs[i].style.width = "500px";
}.bind(this, i));
}
i
var is not defined. – Kodokinputs[i].style.width = "500px";
to thisthis.style.width = "500px";
– Myrnamyrobalanlet
)? edit oh OK, sure. Maybe that should be included in that centralized repository of answers, as this is a pretty common case. – Killigrew