Adding and removing classes from svg elements with jQuery

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');


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.


 * If my-class is set, remove it, otherwise add it

 * You can also add multiple classes

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.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.