I am attempting to assign an onclick event listener to 100 div's that I created in a loop using only vanilla javascript. I have tried various methods that I googled online and cannot get any of them to work. I did read you can do this through a loop (couldn't get that to work either) but that it is bad practice. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Functions: Task 1</title>
<style>
body, html {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
}
p, li {
color: purple;
margin: 0.5em 0;
font-size: 300%;
color: blue;
}
* {
box-sizing: border-box;
}
.preview {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<section class="preview">
</section>
</body>
<script src='java.js'></script>
</html>
let preview = document.querySelector('.preview');
preview.setAttribute('style', 'display: flex; justify-content: center; align-items: center; flex-wrap: wrap;')
function randomColor(input) {
return Math.floor(Math.random() * 255) + 1;
}
for (i = 10*10; i > 0; i--) {
let div = document.createElement('div');
div.className = 'divClass';
div.setAttribute('style', 'height: 10vh; width: 10vw;');
div.style.backgroundColor = 'rgb(' + randomColor(255) + ', ' + randomColor(255) + ', ' + randomColor(255) +')';
preview.appendChild(div);
}
let div = document.querySelector('div');
console.log(div.className);
document.querySelector('div').addEventListener('click', function (event) {
function randomDivColor(input) {
Math.floor(Math.random() * 255) + 1;
document.getElementsByClassName('divClass').style.backgroundColor = 'rgb(' + randomColor(255) + ', ' + randomColor(255) + ', ' + randomColor(255) +')';
}
})