Why .html() doesn't work with SVG selectors using jquery ?

自闭症网瘾萝莉.ら 提交于 2019-11-29 08:00:47

问题


Question can some one tell me how can i convert my SVG element to a string ?

i'm using canvg to convert my SVG to an image.

it has to be render in a canvas first , the canvg() method is expecting a SVG STRING

code :

  function updateChartImage(){
        canvg(document.getElementById('canvas'),expecting ` svg string`);
       var canvas = document.getElementById("canvas") ; 
       var img = canvas.toDataURL("image/png");
       img = img.replace('data:image/png;base64,', '');
       $("#hfChartImg").val(img) ;
       $('#img').attr({ src: img });
        }

i have tried

$('#container svg').html() ; // it gives me an error 
//Uncaught TypeError: Cannot call method 'replace' of undefined 

notice that

  $('#container svg') 
  $('#container').html() // both works fine and

UpDATE

i'm using highcharts the have a getSVG() function that i can pass to the canvg() but the problem is it dosen't get the latest updates , so i have to do it this way , when running the getSVG() function i get the following :

LINK


回答1:


As far as I can recall jQuery's .html() makes use of innerHTML which is meant for html, not svg. SVG's are xml documents, so you can use XMLSerializer()

var svg = document.getElementById('svg_root'); // or whatever you call it
var serializer = new XMLSerializer();
var str = serializer.serializeToString(svg);



回答2:


For the problem you are not getting your svg content,
If only one svg chart is on page then use:

$('svg').html();

and if more than present then please see there is a div of highcharts_container because they create that svg charts. If you are using them.
Then use:

$('id of that div').html();


来源:https://stackoverflow.com/questions/11396372/why-html-doesnt-work-with-svg-selectors-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!