SoFunction
Updated on 2025-03-01

Specific method for changing div color by js loop

When using javascript, if you want to loop through an array, there are two common syntaxes:

Copy the codeThe code is as follows:

 for (var i; i < ; i++) {
     statement;
 }
 for (var i in array) {
     statement;
 }

These two usages seem to be able to do the same thing, but in fact the number of loops in the two loops is generally different.
The source code is as follows:
Copy the codeThe code is as follows:

 <!DOCTYPE html>
 <html>
 <head>
 <style>
 #button{text-align:center;}
 #outer{width:330px; height:100px; margin:10px auto;}
 #outer div{float:left;width:100px;height:100px;margin:0px 5px;background:black;}
 </style>

 <script>
  = function() {
     var obutton = ("button")[0];
     var outer = ("outer");
     var outerDiv = ("div");
     = function() {
         for(var p in outerDiv) outerDiv[p]. = "red";
     };
 };

 </script>
 </head>
 <body>
 <div >
<button>Click to turn red</button>
 </div>
 <div >
     <div></div>
     <div></div>
     <div></div>
 </div>
 </body>
 </html>

This code uses the for - in statement to loop, and it seems to be fine.
However, when debugging the browser, an error will be reported:
"Uncaught TypeError: Cannot set property 'background' of undefined"
Why is this happening?
If we change the content of stament, we will find the problem:
 for(var p in outerDiv) alert(p);
The result output is: 0 1 2 length item
So, when the property gets length and item, try to call the style method again, of course it is undefined. Modifications are as follows:

Copy the codeThe code is as follows:

 <!DOCTYPE html>
 <html>
 <head>
 <style>
 #button{text-align:center;}
 #outer{width:330px; height:100px; margin:10px auto;}
 #outer div{float:left;width:100px;height:100px;margin:0px 5px;background:black;}
 </style>

 <script>
  = function() {
     var obutton = ("button")[0];
     var outer = ("outer");
     var outerDiv = ("div");
     = function() {
         for (var i = 0; i < ; i++){
             outerDiv[i]. = "red";
         }
     };
 };

 </script>
 </head>
 <body>
 <div >
<button>Click to turn red</button>
 </div>
 <div >
     <div></div>
     <div></div>
     <div></div>
 </div>
 </body>
 </html>