anraT
anraT

Reputation: 543

change information in svg string

I have a svg string. In order to get information, I got the answer in this link how to get information from a svg string in javascript? usign jquery. But does anyone know how to change any atribute? for example how to change the height of the rect of the Layer 2 to other value? How to add a new attribute which doen't exist? for example to add stroke-dasharray="1,1" in the rect of the Layer 2? Thanks

<svg width="612" height="394" xmlns="http://www.w3.org/2000/svg">
 <g>
     <title>Layer 1</title>
     <rect id="svg_1" height="152" width="265" y="44" x="91" stroke-width="5" stroke="#000000" fill="#FF0000"/>
 </g>
 <g>
     <title>Layer 2</title>
     <rect id="svg_2" height="125" width="151" y="157" x="399" stroke-width="5" stroke="#000000" fill="#FF0000"/>
 </g>
</svg>

My string es for exemple: str="<svg width........</g></svg>"

Upvotes: 1

Views: 1474

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195962

Just set a value to it instead of just retrieving..

With jquery you can use the second parameter of .attr() to use a value to be set...

$('#svg_2').attr('height', 200);

and

$('#svg_2').attr('stroke-dasharray', "1,1");

Demo at http://jsfiddle.net/gaby/FX67f/1/


If you want the actual string, and the svg is not in the DOM but just a variable then you can do

var fixedstr = $(str).wrapAll('<div>')
                     .find('g:eq(1) rect')
                     .attr('height', 200)
                     .attr('stroke-dasharray', "1,1")
                     .closest('div')
                     .html();

First we create a jquery object out of it, and then we wrap it in a div element so we can later get its .html() (the actual svg string).

Find the rect in the second g element with .find('g:eq(1) rect') and then use the .attr() to alter its attributes..

Finally use .closest('div') to go back up to our container div, and use .html() to get the contents..

Demo for this version at http://jsfiddle.net/gaby/FX67f/2/

Upvotes: 2

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

I have not tried that but it should work: Set a new value:

$("svg").find("rect#svg_2").attr("height", new_val);

Upvotes: 0

Related Questions