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.');
});
If you have dynamic classes or don't know what classes could be already applied then this method I believe is the best approach:
There is element.classList in the DOM API that works for both HTML and SVG elements. No need for jQuery SVG plugin or even jQuery.
Just add the missing prototype constructor to all SVG nodes:
You can then use it this way without requiring jQuery:
All credit goes to Todd Moto.
One workaround could be to addClass to a container of the svg element:
After loading
jquery.svg.js
you must load this file:http://keith-wood.name/js/jquery.svgdom.js
.Source: http://keith-wood.name/svg.html#dom
Working example: http://jsfiddle.net/74RbC/99/
jQuery does not support the classes of SVG elements. You can get the element directly
$(el).get(0)
and useclassList
andadd / remove
. There is a trick with this too in that the topmost SVG element is actually a normal DOM object and can be used like every other element in jQuery. In my project I created this to take care of what I needed but the documentation provided on the Mozilla Developer Network has a shim that can be used as an alternative.example
An alternative all tougher is to use D3.js as your selector engine instead. My projects have charts that are built with it so it's also in my app scope. D3 correctly modifies the class attributes of vanilla DOM elements and SVG elements. Though adding D3 for just this case would likely be overkill.