简体   繁体   中英

How to get the svg in string format of a g element?

I would like to know if it is possible to get the contents in ag 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 ag 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 ag element (in this case a layer) and get it's content.

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.

I'm not sure if this is what you meant on getting the contents of ag 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM