0

I would like to know if it is possible to get the contents in a g element of an svg element with jquery or javascript?

<svg>
<g><path>...</path></g>
</svg>
<script>
    var contents = $("div").append($("svg g").clone()).html();
</script>

This will work normally with the path or any part inside a g element but not the g element itself. Additionally for some reason if I ran this code:

<script>
    var contents = $("div").append($("path").parent().clone()).html();
</script>

I can get the contents, but for the project I need to be able to match a g element (in this case a layer) and get it's content.

Justin T. Watts
  • 547
  • 1
  • 4
  • 16
  • Wanted to make a correction the the understanding of this entry, they both work without erroring but the first will get far more than just the g tag, and the second will just get the g tag. – Justin T. Watts Oct 09 '13 at 01:59

2 Answers2

0

It seems to work but there are a couple of problems with your examples.

First you can't use html() on an SVG element (see answer here: Why .html() doesn't work with SVG selectors using jquery ?) so it depends what you want to do with the g element.

Second you're appending the g element to the div, but it needs to live inside an svg element. So for a page like this:

<div>
    <svg>
        <g><path d='m10,10l10,0,0,-10,-10,0'></path></g>
    </svg>
</div>

You can clone the g element like this:

g = $("svg g").clone();
$('svg').append(g);

// Move the cloned square
g.children().first().attr('d', 'm100,100l10,0,0,-10,-10,0');

So now you can do whatever you want with the variable g in that example (see the linked answer if you need to start editing the inner XML directly rather than use jQuery to modify the contents).

Fiddle: http://jsfiddle.net/SpaceDog/sXbE3/

To get the string you need to use XMLSerializer as described in the linked answer above:

var s = new XMLSerializer();
var str = s.serializeToString(g[0]);
console.log(str);

Here I'm using g[0] to get the DOM element of g. If you just want the contents try (g.children().first())[0]. I've updated the fiddle.

However, depending on what you're going to do with the string you might not need to do that. jQuery can modify the elements directly -- it depends what you want to do.

Community
  • 1
  • 1
SpaceDog
  • 3,249
  • 1
  • 17
  • 25
  • The way to do that is in the other answer I linked, I've updated the fiddle and edited my answer to show an example. – SpaceDog Oct 09 '13 at 03:45
0

I'm not sure if this is what you meant on getting the contents of a g element. I've tried manipulating it using a simple script.

    $("[name=getElement]").click(function(){
     $('.getThisElement').hide();
     $("#test"+$(this).val()).show('fast');

Try this JSfiddle I've created.

novice
  • 157
  • 5
  • 15