I have 8 paragraphs and I want to toggle the class 'one-active' when clicking on each of them, while removing the active class from the others. I currently have the code working for two paragraphs, but it's too lengthy for all eight. How can I achieve the same functionality with fewer lines of code?
let paragraphs = document.querySelectorAll('p');
function changeColor(index){
paragraphs.forEach((p, i) => {
if(i === index){
p.classList.toggle('active');
} else {
p.classList.remove('active');
}
});
}
paragraphs.forEach((p, i) => {
p.addEventListener('click', () => {
changeColor(i);
});
});
<style>
p{
color: rgb(11, 28, 47);
background-color: rgb(255, 255, 255);
}
p.active{
color: rgb(255, 255, 255);
background-color: rgb(11, 28, 47);
}
</style>
<p>COSA È</p>
<p>COSA È</p>
<p>COSA È</p>
<p>COSA È</p>
<p>COSA È</p>