Assuming this:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
});
</script>
</head>
<body>
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px">
</svg>
</body>
Why don't I see anything?
I haven't seen someone mention this method but
document.createElementNS()
is helpful in this instance.You can create the elements using vanilla Javascript as normal DOM nodes with the correct namespace and then jQuery-ify them from there. Like so:
The only down side is that you have to create each SVG element with the right namespace individually or it won't work.
Found an easy way which works with all browsers I have (Chrome 49, Edge 25, Firefox 44, IE11, Safari 5 [Win], Safari 8 (MacOS)) :
I would suggest it might be better to use ajax and load the svg element from another page.
Where href is the location of the page with the svg. This way you can avoid any jittery effects that might occur from replacing the html content. Also, don't forget to unwrap the svg after it's loaded:
If the string you need to append is SVG and you add the proper namespace, you can parse the string as XML and append to the parent.
A much simpler way is to just generate your SVG into a string, create a wrapper HTML element and insert the svg string into the HTML element using
$("#wrapperElement").html(svgString)
. This works just fine in Chrome and Firefox.The accepted answer by Bobince is a short, portable solution. If you need to not only append SVG but also manipulate it, you could try the JavaScript library "Pablo" (I wrote it). It will feel familiar to jQuery users.
Your code example would then look like:
You can also create SVG elements on the fly, without specifying markup: