Skip to content Skip to sidebar Skip to footer

Proper Code For A For Loop In Javascript?

Is this proper code for javascript? var inputsClass = document.getElementsByClassName('inputClass'); var errorSpan = document.getElementsByClassName('errorSpan'); for(var index=0;

Solution 1:

You have a couple issues. The first issue is that your onclick handler function is called sometime LATER, long after your for loop has finished. That means that the value of your loop variable index is going to be at the end of the sequence and not valid inside the event handler function.

You can fix the first issue by adding a closure that captures the index value separately for each callback function.

The second issue is that you can't do inputsClass[i].errorSpan. errorSpan isn't a valid property of inputsClass[i].

It's not entirely clear what you're trying to do with the errorSpan. If you want to find the errorSpan that is contained within the particular inputClass object, then you would do inputClass[i].getElementsByClassname("errorSpan")[0]. If inputClass and errorSpan are parallel arrays and from the i inputClass, you want to refer to the ierrorSpan, then you would do errorSpan[i]. Here are the two versions:

Find errorSpan contained within inputsClass:

var inputsClass = document.getElementsByClassName("inputClass");

for(var index=0; index < inputsClass.length;index++ ){
    (function(i) {
        inputsClass[i].onclick = function() {
            inputsClass[i].getElementsByClassName("errorSpan")[0].style.color="black";
        }
    })(index);
}

Use parallel arrays of inputsClass and errorSpan:

var inputsClass = document.getElementsByClassName("inputClass");
var errorSpan = document.getElementsByClassName("errorSpan");

for(var index=0; index < inputsClass.length;index++ ){
    (function(i) {
        inputsClass[i].onclick = function() {
            errorSpan[i].style.color="black";
        }
    })(index);
}

If you show your actual HTML and explain what you are trying to accomplish rather than just post a piece of code that doesn't work, we can offer more complete advice.

Post a Comment for "Proper Code For A For Loop In Javascript?"