1

I have simple HTML page with svg like this:

<div id="plan">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g id="layer3">
   <rect width="105.71429" height="80" x="351.42856" y="152.36218" id="rect1" style="fill:#008000"></rect>
   <rect width="120" height="85.714287" x="500" y="389.50504" id="rect2" style="fill:#008000"></rect>
</g>
</svg>
</div>

How i can get the string:

<rect width="105.71429" height="80" x="351.42856" y="152.36218" id="rect1" style="fill:#008000"></rect> 

from this svg. I can use jquery and jquery svg. I try:

    $(document).ready(function() {
    console.log($("#plan #rect1")[0]);
})

In console i take this string, but i must get string in variable like this:

var str = $("#plan #rect1")[0];

variable str is [object SVGRectElement] [enter link description here]1

VasyambaTula
  • 13
  • 1
  • 1
  • 5

2 Answers2

5

To combine the previous answers (which were not clear for me at first) the way to get the SVG string is following:

var str = $('<div>').append($('#plan #rect1').clone()).html(); 
Iwo Banas
  • 892
  • 8
  • 12
1
$('#rect1')[0]

This should help. If you want to access tag instead of jQuery element, use [] to get encapsulated element.

Edit :

This should do the trick for you.

The solution explained is to wrap your selection into another tag and call .html() on it to display its content.

Don't forget the .clone() call before appending it into your temp div, otherwise you will have some trouble in your html :)

Community
  • 1
  • 1
Mordhak
  • 2,646
  • 2
  • 20
  • 14
  • I use var str = $("#plan > #rect1")[0]; alert(str); but str is undefined – VasyambaTula Mar 26 '12 at 13:03
  • $("#plan > #rect1") will search the next child in plan which has id "rect1", but your child is a 'g' tag. That's why $("#plan > #rect1") returns nothing. ">" means direct child. Use $("#plan #rect1") instead. – Mordhak Mar 26 '12 at 13:08
  • I use: var str = $("#plan #rect1").html(); alert(str); it made error - Uncaught TypeError: Cannot call method 'replace' of undefined. i use: var str = document.getElementById('rect1'); var st = str.innerHTML; alert(st); but var st is undefined – VasyambaTula Mar 27 '12 at 09:46
  • Just use $("#plan #rect1")[0] as i write first. It works for me. [jsfiddle link](http://jsfiddle.net/GU3Yn/1/) – Mordhak Mar 27 '12 at 12:12
  • Ok, thanks, its work for console, but i must get it's string in variable. If i write $("#plan #rect1")[0] in variable, variable is [object SVGRectElement] [link](http://jsfiddle.net/GU3Yn/3/) – VasyambaTula Mar 28 '12 at 11:16
  • Great ! (don't forget to validate the answer) – Mordhak Mar 29 '12 at 08:42