Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class on svg path element

Tags:

html

jquery

svg

In my project I have an SVG world map with different paths with different id's and one class of map-path. For each country click I want to add class on each path. My HTML is like this:

<svg viewBox="">
    <path id="map_1" class="map-path" ......>
    <path id="map_2" class="map-path" ......>
    <path id="map_3" class="map-path" ......>
    <path id="map_4" class="map-path" ......>
    <!-- more <path /> elements... -->
</svg>
like image 440
Naveen Sadasivan S Avatar asked Mar 21 '16 11:03

Naveen Sadasivan S


1 Answers

JQuery function addClass() will not work here and can't add a class to an SVG.

Use .attr() instead :

$('body').on('click','.map-path',function() {
    $(this).attr("class", "map-path newclass");
});

You could use pure js solution with setAttribute() method :

$('body').on('click','.map-path',function(e) {
    e.target.setAttribute("class", "map-path newclass");
});

Or use classList.add() that works in modern browsers :

$('body').on('click','.map-path',function(e) {
    e.target.classList.add('newclass');
});

Hope this helps.

like image 187
Zakaria Acharki Avatar answered Sep 27 '22 17:09

Zakaria Acharki