0

I have an svg map image and I want to loop over it's path element and add add a class. I get the above error nonetheless. Here is my code

document.addEventListener("DOMContentLoaded", function() {
svg = document.getElementsByTagName('path');        

for(i=0; i<svg.length;i++)
  {
    svg[i].addEventListener('mouseover', function(){
        svg[i].setAttribute('class','svgclass');
    });
  }

});

WHat am i doing wrong? Thanks

Sonia
  • 1,909
  • 1
  • 11
  • 13
Patrick Obafemi
  • 908
  • 2
  • 20
  • 42

1 Answers1

2

svg[i] is undefined at the point mouseover occurs. Probably because i is equal to the highest value of the loop in every event handler, and at least one of the elements has been removed from the collection.

A better alternative would be to use this to reference the element which raised the event instead. Note the use of classList.add() as well; this will append a class to any existing ones instead of removing all existing.

for (i = 0; i < svg.length; i++) {
  svg[i].addEventListener('mouseover', function() {
    this.classList.add('svgclass');
  });
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Am trying to call it in the console of my browser without the function around it. This time i get the following error 'Uncaught TypeError: Cannot read property '37' of undefined at SVGPathElement' – Patrick Obafemi Sep 24 '19 at 13:32