简体   繁体   中英

How can I extract the html code for a DOM object generated by javascript?

I am generating a svg object in a html document using java script. Something like this:

mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
myPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
mySvg.appendChild(myPath);

Is there a javascript command to extract what the resulting html code would be?

ie

"<svg>...<path>...</path>...</svg>"

I want to then save this part as a string variable.

Thanks, Wendy

Yeah...Put your svg tag into a div and then get the Html of that div.

<div id="container"></div>
$('#container').append('mySvg');

And for the whole svg as an html, you can do this:

var svgHtml = $('#container').html();

For the string:

var svgHtml = document.getElementById('container').innerText;

You can use the innerHTML to get the html text for an element

mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
myPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
mySvg.appendChild(myPath);

document.getElementById('x').appendChild(mySvg);

console.log(document.getElementById('x').innerHTML)

Fiddle

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