This is an extension to my previous question javascript dynamically adding and removing classes
As per the answer given, it uses a forEach
loop but I am trying to use a for
loop and implement the same:
function test() {
var paragraphs = document.querySelectorAll("#divid p[id ^= 'p']");
for(index =0; index < paragraphs.length; index++) {
paragraphs[index].addEventListener('click', (e) => {
for (i = 0; i < index; i++) {
paragraphs[i].classList.remove('active');
}
for (i = index; i < paragraphs.length; i++) {
paragraphs[i].classList.add('active');
}
});
}
}
But I am getting the following error:
11 Uncaught TypeError: Cannot read property 'classList' of undefined
at HTMLSpanElement.paragraphs.(anonymous function).addEventListener
I also want to remove the special symbol =>
in above code and solve the issue.