JSFiddle - React, Tailwind, and code Playground
HTML
<div id="parentElem">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
CSS
#parentElem {
display: flex;
flex-direction: row;
}
.box {
background-color: #fff;
border: 1px solid black;
width: 48px;
height: 48px;
}
JavaScript
// Grab all input boxes.
var inputBoxes = document.getElementsByClassName('box');
// Turn node list into an array so we can use array methods.
inputBoxes = Array.from(inputBoxes);
// Grab the parent element.
var parentElem = document.getElementById('parentElem');
// Attach onclick event to the parent element.
parentElem.addEventListener('click', function(event) {
if (event.target.classList.contains('box')) {
// White by default.
inputBoxes.forEach(function(box) {
box.style.backgroundColor = 'white';
})
// Grab the index of the clicked box.
var indexOfClickedBox = inputBoxes.indexOf(event.target);
// Red for each box until clicked box.
inputBoxes.forEach(function(box, i) {
if (i <= indexOfClickedBox)
box.style.backgroundColor = 'red';
})
}
});