[GIS] Leaflet / JQuery -cannot add or remove class to divIcon marker

geojsoniconjqueryleafletzoom

(this is related to a previous question of mine)

I am adding a divIcon (an svg) as the icon for features in a geoJSON, using Leaflet.
I can add a class to the html property of the icon, but I cannot seem to dynamically add or remove the class using jQuery. I would like to do this to change the size of the icon at different zoom levels (unless anyone else has a better idea how to do this?)

code snippets below:

this part works as expected; the icon is the size given in the css class (although the 'size' property seems to be ignored)

var icon = L.divIcon({"iconSize":new L.Point(50, 50), "iconAnchor": AnchorIcon,  "popupAnchor": PopIcon, html: '<svg id="thisIcon" class="thisIcon15" ><use xlink:href="#marker"/></svg>'});

but if I try to dynamically find if this class exists on a zoom event with JQuery, the return value is false:

map.on('zoomend', function(e) {
  console.log( $('#thisIcon').hasClass("thisIcon15")  ); // false

I tried directly referencing 'svg' in the JQuery call as well…no luck.

EDIT: I found that 'addClass' and 'removeClass' cannot be used directly with svgs (LINK).

I tried the workaround suggested in that link, but although I get the new SVG at the right size, the old one does not disappear; instead the resized SVG appears on top of the old one. From what I can see, the size property given in the icon declaration is not being honored. If i could find a way to add all the different sized icons to each point, then toggle the opacity of each one, that could work.

Best Answer

Here's a codepen example that shows how to add a class to an SVG. No jQuery required.

document.getElementsByTagName('svg')[0].classList.add("anotherclass");
console.log(document.getElementsByTagName('svg')[0].classList)

https://codepen.io/anon/pen/KQLgKL?editors=1111