最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How get SVG code from html page, using jQuery or JavaScript? - Stack Overflow

programmeradmin0浏览0评论

I have simple HTML page with svg like this:

<div id="plan">
<svg xmlns="" 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

I have simple HTML page with svg like this:

<div id="plan">
<svg xmlns="http://www.w3/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

Share Improve this question edited Apr 20, 2018 at 16:28 homeostasis 134 bronze badges asked Mar 26, 2012 at 12:19 VasyambaTulaVasyambaTula 131 gold badge1 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

To bine 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(); 
$('#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 :)

发布评论

评论列表(0)

  1. 暂无评论