I just want to go in and say that I have found a more elegant solution that allows you to use jQuery with SVG elements, but without the jQuery SVG library (which is no longer updated and has some problems with jQuery 1.8 or higher). Just use this function:
createSVGElement= function(element) { return $(document.createElementNS('http://www.w3.org/2000/svg', element)); }
it creates an SVG element in the SVG namespace and encapsulates it using jQuery, once the element is created in the right namespace, you can freely use it with jQuery:
Then you can use the function as follows:
var $myGradient= createSVGElement('linearGradient') .attr( { id:"MyGradient" }); //if you dont need `defs`, skip this next line var $myDefs = createSVGElement('defs'); createSVGElement('stop') .attr({ offset: "5%", "stop-color": "#F60" }) .appendTo($myGradient); createSVGElement('stop') .attr({ offset:"95%", "stop-color":"#FF6" }) .appendTo($myGradient); //Use this if you already have `defs` $('svg defs').prepend($myGradient); //Use this if you dont have `defs` $('svg').prepend($myDefs); $('svg defs').prepend($myGradient);
It is not as compact as you can be, because you need to create each element manually, but it is much better than manipulating everything with DOM methods.
A small note. The jQuery.attr () function assumes that all attributes have a lower value, which does not apply to SVG elements (for example, the viewBox attribute in <svg> tags). To get around this, when setting up the uppercase attributes, use something like this:
$("svg")[0].setAttribute("viewBox", "0 0 1000 1000");
Hoffmann
source share