JSFiddle - React, Tailwind, and code Playground

HTML

<div id="div1" style="width:20px; height:20px; background-color: yellow;"></div>

<div id="div2" style="width:20px; height:20px; background-color: blue;"></div>

<div id="div3" style="width:20px; height:20px; background-color: green;"></div>

<div id="div4" style="width:20px; height:20px; background-color: red;"></div>

JavaScript

var arr = new Array();

arr.push(document.getElementById("div1"));
arr.push(document.getElementById("div2"));
arr.push(document.getElementById("div3"));
arr.push(document.getElementById("div4"));
    for(var i = 0; i < arr.length; i++){
        (function(i){ //i inside this function is a local var; not affected by i++
            arr[i].onclick = function(){
                alert(i);
                return false;
            };
        })(i); //Invoke the function, pass variable i 
    }