Можно использовать циклы, а можно
делегирование событий:
<head>
<style>
span{
display:inline-block;
padding:1em;
}
</style>
</head>
<body>
<div id="spans">
<span class="span">#1</span>
<span class="span">#2</span>
<span class="span">#3</span>
<span class="span">#4</span>
<span class="span">#5</span>
</div>
<div id="spans2">
<span class="span">#a</span>
<span class="span">#b</span>
<span class="span">#c</span>
<span class="span">#d</span>
<span class="span">#e</span>
</div>
<script>
document.getElementById('spans').addEventListener('click', (event)=>{
const t = event.target.closest('span');
if(t){event.target.style.backgroundColor="purple"}
});
for (let span of document.querySelectorAll('#spans2 span')) {
span.onclick = () => {
span.style.backgroundColor = "gold"
}
}
</script>
</body>