0

I can remove the line linearGradient with jQuery in a SVG but I can't add it. Why?

HTML

<textarea>
<linearGradient y2="1" x2="1" id="g" spreadMethod="reflect">
<stop stop-color="#F00" offset="0"/>
<stop stop-color="#F0F" offset="1"/>
</linearGradient>
<style type="text/css" >
<![CDATA[
    path {  stroke: #009900;  
            stroke-width: 0.1;  
            fill:url(#g);}
]]>
</style>
</textarea>

JS

$('#remove').click(function()
{
    $('svg style, svg linearGradient').remove(); 
});
$('#set').click(function()
{
    $('svg').prepend($('textarea').val());       
});

Fiddle http://jsfiddle.net/qt2ony7v/

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Peter
  • 11,413
  • 31
  • 100
  • 152
  • You can't use jQuery for svg elements directly. – defghi1977 Aug 15 '14 at 00:41
  • but why does the remove button work? – Peter Aug 15 '14 at 02:22
  • Try `$clone = $('svg style, svg linearGradient').clone();`, then SET = `$('svg').prepend($clone)` , check with `console.log($clone)`. `$clone` is a DOM element while `.val()` is a string. You have to [create DOM element from HTML string](http://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro) – Alvin K. Aug 15 '14 at 05:48
  • HTMLDOM and SVGDOM have same api partially but SVGElement doesn't have innerHTML property jQuery uses in prepend method perhaps. – defghi1977 Aug 15 '14 at 06:42
  • 2
    @defghi1977 innerHTML is available on svg elements too these days, see http://stackoverflow.com/a/9826866/109374 – Erik Dahlström Aug 15 '14 at 07:52
  • Oh, I don't know this spec, thank you! – defghi1977 Aug 15 '14 at 08:06

1 Answers1

0

If you open the inspector you'll see that the style element was being removed but the linearGradient element was not being removed. Also, everything from the textarea was being prepended to the SVG but the CSS wasn't taking effect.

Instead try this approach:

http://jsfiddle.net/qt2ony7v/1/

In that fiddle, I'm not using a style element but applying the style to all the paths using a g element.

<g id="group" stroke="#009900" stroke-width="0.1" fill="url(#g)">
    <path />
    <path />
</g>

Then use jQuery to change the attributes:

$('#group').attr('fill', 'url(#g)');
cuth
  • 514
  • 6
  • 8