I am using jQuery SVG. I can't add or remove a class to an object. Anyone know my mistake?
The SVG:
<rect class="jimmy" id="p5" x="200" y="200" width="100" height="100" />
The jQuery that won't add the class:
$(".jimmy").click(function() {
$(this).addClass("clicked");
});
I know the SVG and jQuery are working together fine because I can target the object and fire an alert when it's clicked:
$(".jimmy").click(function() {
alert('Handler for .click() called.');
});
I wrote this in my project, and it works... probably;)
examples
I use Snap.svg to add a class to and SVG.
http://snapsvg.io/docs/#Element.addClass
jQuery 3 does not have this problem
One of the changes listed on the jQuery 3.0 revisions is:
One solution for this issue would be to upgrade to jQuery 3. It works great:
The Problem:
The reason the jQuery class manipulation functions do not work with the SVG elements is because jQuery versions prior to 3.0 use the
className
property for these functions.Excerpt from jQuery
attributes/classes.js
:This behaves as expected for HTML elements, but for SVG elements
className
is a little different. For an SVG element,className
is not a string, but an instance ofSVGAnimatedString
.Consider the following code:
If you run this code you will see something like the following in your developer console.
If we were to cast that
SVGAnimatedString
object to a string as jQuery does, we would have[object SVGAnimatedString]
, which is where jQuery fails.How the jQuery SVG plugin handles this:
The jQuery SVG plugin works around this by patching the relevant functions to add SVG support.
Excerpt from jQuery SVG
jquery.svgdom.js
:This function will detect if an element is an SVG element, and if it is it will use the
baseVal
property of theSVGAnimatedString
object if available, before falling back on theclass
attribute.jQuery's historical stance on the issue:
jQuery currently lists this issue on their Won’t Fix page. Here is the relevant parts.
Evidently jQuery considered full SVG support outside the scope of the jQuery core, and better suited for plugins.
jQuery 2.2 supports SVG class manipulation
The jQuery 2.2 and 1.12 Released post includes the following quote:
Example using jQuery 2.2.0
It tests:
If you click on that small square, it will change its color because the
class
attribute is added / removed.Edit 2016: read the next two answers.
element.classList.add('newclass')
works in modern browsersJQuery (less than 3) can't add a class to an SVG.
.attr()
works with SVG, so if you want to depend on jQuery:And if you don't want to depend on jQuery:
Inspired by the answers above, especially by Sagar Gala, I've created this API. You may use it if you don't want or can't upgrade your jquery version.