rob.m rob.m - 1 month ago 5
Javascript Question

How to save a list of classes using javascript to compare them against other classes later?

I have a series of polygons :

<svg>
<path class="_1600 _1500 _1400 leaflet"></path>
<path class="_1300 _1700 _1900 leaflet"></path>
<path class="_1600 _1400 _1800 leaflet"></path>
</svg>


And buttons:

<button class="_1600 _1500"></button>
<button class="_1600 _1300 _1200"></button>
<button class="_1300 _1200 _1700 _1800"></button>
<button class="_1300 _1200 _1100 _1900"></button>


I need to assign a class to it on a click and this is how I do it and works fine:

On click:

this.getElement().classList.add("active");


Now the polygons become:

<svg>
<path class="_1600 _1500 _1400 leaflet"></path>
<path class="active _1300 _1700 _1900 leaflet"></path>
<path class="_1600 _1400 _1800 leaflet"></path>
</svg>


How can I save the list of classes of the clicked element (to which I also have added
.active
after a click)?
I would like to save them so that I can later comprare this list for any match with another list of classes and if any match, attach a
.active
class to the matching elements.

I must use:

function onEachFeature(feature, layer) {
layer.on({
click: panelShow
});
}

function panelShow(e) {
$("path").removeClass("active");
this.getElement().classList.add('active');
}

Answer

You can use className to get a space-separated string containing all the classes.

this.getElement().className;

If you want to have something more fancy, like a static classList copy, you can always create a dummy element:

function staticClassListCopy(element) {
  var dummy = document.createElement('div');
  dummy.className = element.className; // import classes
  return dummy.classList;
}

This object will be an array-like, so you can iterate it easily to do the desired comparisons.