I am using while loop to attach an event in element. However event is successfully added but the function also throw error on console. if I use pre-increment then its worked fine. I just want to know what is the problem with post increment. fiddle
var elements= document.getElementsByTagName('*'), i;
i=0;
while(elements[i++]){
if(elements[i].className=='c') {
elements[i].addEventListener('click',function() {
alert(this.className)
})
}
}
3 Answers 3
Your i++ in the loop header means that the value of i is one greater than it was when the test was made. You'll skip element 0 and try to process the element past the end of the list.
So when this runs:
while (elements[i++])
the element index that's tested will be 0 through the last element, the value of i after that point will be one more than that. That's because i++ means "use the value of i but increment it afterwards".
When you used pre-increment (++i) it was still wrong, unless you initialized i to -1.
Really this is why we have the for loop:
for (i = 0; elements[i]; i++) {
// ...
}
That way the value of i remains the same from the loop test through the end of the loop body.
Comments
Try this
var elements = document.getElementsByTagName('*'),
i = 0;
while (elements[i]) {
if (elements[i].className == 'c') {
elements[i].addEventListener('click', function (e) {
alert(this.className)
})
}
i++;
}
Comments
Don't use the ++ operator. You should utilize aggregate operations instead. They are a useful abstraction layer against loops. They allow you think of iteration without concern for the intricacies of side-effecting operations like incrementing.
var elements = document.getElementsByTagName('*');
function toArray(list) {
return Array.prototype.slice.call(list);
}
toArray(elements).forEach(function (element) {
if (element.className === 'c') {
element.addEventListener('click', function () {
alert(this.className);
});
}
});
1 Comment
forEach function, among other things.