0

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)
        })
    }
}
0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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++;
}

Demo: http://jsfiddle.net/r19r7djb/3/

Comments

1

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

IE9+. If you require IE8 or lower support, you can use a library like Lodash (lodash.com), which provides a forEach function, among other things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.