33

I'm using custom divIcons for my Leaflet markers. I want to add a border to whatever marker I click on, with some simple CSS:

.selectedMarker {
border: 10px solid gold;
}

However, the following with jQuery doesn't work:

$(marker).addClass('selectedMarker');

Then I tried to use Leaflet's own addClass() method. I tried to call use it in the following ways:

marker.addClass('selectedMarker');
L.addClass(marker, 'selectedMarker');
addClass(marker, 'selectedMarker');
DomUtil.addClass(marker, 'selectedMarker');

None of these work. How do I add the selectedMarker class to my marker?

yesman
  • 7,165
  • 15
  • 52
  • 117

4 Answers4

29

In 1.0 and 0.7 you can use L.DomUtil to add remove classes from a DOM element:

L.DomUtil.addClass(marker._icon, 'className');
L.DomUtil.removeClass(marker._icon, 'className');
bgeo
  • 446
  • 5
  • 6
22

I have done it by adding a class to the marker with

var marker = L.marker(loc);
marker.on('click', function() {
    $(marker._icon).addClass('selectedMarker');
}

and then use the css

.leaflet-marker-icon.selectedMarker{
  //your css
}
r8n5n
  • 2,059
  • 17
  • 23
20

without using jQuery,

marker._icon.classList.add("className");
MK4
  • 725
  • 8
  • 24
  • 1
    Confirmed this works, thanks. This is the best method to do it I think. Unfortunately `classList` remains undefined until the user clicks it, so can't add a class right after creating it with this method. Also, tip for those using leaflet markercluster, it's in `event.layer._icon`. – davidtgq Mar 04 '17 at 03:44
  • I had to do this with polygons. `layer._path.classList.add("className")` worked for me in that case. – aggregate1166877 Jan 15 '19 at 00:13
  • Use `marker._path` for `L.circleMarker` too. Within a click handler you can obtain reference to this from `event.target._path` – Greg K Oct 23 '20 at 16:23
0

I am using the marker = new Marker() syntax, and then marker._icon doesn't work. What solved this for me was to just set a new icon initialized with another class, like so

const originalIcon = new Icon({
    iconUrl: iconImg,
    iconSize: [50, 50],
});
const iconWithNewClass = new Icon({
    iconUrl: iconImg,
    iconSize: [50, 50],
    className: 'new-class',
});

...

marker.setIcon(iconWithNewClass);
Matthias
  • 3,160
  • 2
  • 24
  • 38