This article mainly introduces how to change the div color in javascript loop. For more information about how to use javascript to traverse an array cyclically, there are two commonly used syntaxes:
The Code is as follows:
For (var I; I <array. length; I ++ ){
Statement;
}
For (var I in array ){
Statement;
}
These two methods seem to be able to do the same thing, but in fact the number of cycles of the two cycles is generally different.
The source code is as follows:
The Code is as follows:
Script
Window. onload = function (){
Var obutton = document. getElementsByTagName ("button") [0];
Var outer = document. getElementById ("outer ");
Var outerDiv = outer. getElementsByTagName ("p ");
Obutton. onclick = function (){
For (var p in outerDiv) outerDiv [p]. style. background = "red ";
};
};
Script
Click to change to red
This Code uses the for-in statement for loop. It seems that there is no problem.
However, an error is reported during browser debugging:
"Uncaught TypeError: Cannot set property 'background' of undefined"
Why?
If we change the stament content, we will find the problem:
For (var p in outerDiv) alert (p );
Result output: 0 1 2 length item
Therefore, when the property obtains the length and item, it tries to call the style method, of course, undefined. Modify as follows:
The Code is as follows:
Script
Window. onload = function (){
Var obutton = document. getElementsByTagName ("button") [0];
Var outer = document. getElementById ("outer ");
Var outerDiv = outer. getElementsByTagName ("p ");
Obutton. onclick = function (){
For (var I = 0; I <outerDiv. length; I ++ ){
OuterDiv [I]. style. background = "red ";
}
};
};
Script
Click to change to red