A few days ago I wanted to toggle a class on an svg element. Not sure anymore, but I think I wanted to show/hide it. jQuery was already loaded and used in the project so I added the class with $('#js_svg-element').addClass('my-class');
Nothing happened. I inspected my code over and over again and couldn't find anything that's wrong, so I asked my dear friend Google and found out that you can't add/remove classes to/from svg elements with jQuery. Bummer. Luckily, there are two solutions:
jQuery .attr()
One solution is to fall back to the .attr() method of jQuery, like that:
/**
* Instead of .addClass('my-class')
*/
$('#js_svg-element').attr('class', 'my-class');
/**
* Instead of .removeClass('newclass')
*/
$('#js_svg-element').attr('class', '');
The .attr()
method replaces the complete attribute, so if you want to add a class to existing ones you have to list them too, which can make this workaround a little tedious:
/**
* If #js_svg-element already has the classes a-class and another-class
*/
$('#js_svg-element').attr('class', 'a-class another-class my-class');
classList
The other solution is to use the Web API Interface Element.classList
. classList
has three different write possibilities: .add
, .remove
or .toggle
. Sadly IE9 and Opera Mini don't support classList
.
$('#js_svg-element').classList.add('my-class');
$('#js_svg-element').classList.remove('my-class');
/**
* If my-class is set, remove it, otherwise add it
*/
$('#js_svg-element').classList.toggle('my-class');
/**
* You can also add multiple classes
*/
$('#js_svg-element').classList.add('my-class','my-other-class');
If you want to know more about the classList Web API Interface, the MDN has tons of information and a Javascript Shim which should make it work in IE9 and Opera Mini. But in my case I'm not a fan of throwing so much JS on the table just to make this work for adding/removing a class from a single svg element.