Assuming this:

 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript">
  $("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
 <svg xmlns:svg="" xmlns="" viewBox="0 0 200 100" width="200px" height="100px">

Why don't I see anything?

Solution 1

When you pass a markup string into $, it's parsed as HTML using the browser's innerHTML property on a <div> (or other suitable container for special cases like <tr>). innerHTML can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that <circle> was supposed to be in the SVG namespace.

innerHTML is not available on SVGElementit is a property of HTMLElement only. Neither is there currently an innerSVG property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.

HTML5 promises to let you use <svg> without an xmlns inside a plain HTML (text/html) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use innerHTML even though they look like part of an HTML document.

However, for today's browsers you must use XHTML (properly served as application/xhtml+xml; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the < symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns declaration. example:

<!DOCTYPE html>
<html xmlns=""><head>
    <svg id="s" xmlns=""/>
    <script type="text/javascript">
        function makeSVG(tag, attrs) {
            var el= document.createElementNS('', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;

        var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
        circle.onmousedown= function() {

*: well, there's DOM Level 3 LS's parseWithContext, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using innerHTML, then transfer it to the desired target. It'll likely be a bit slower though:

<script type="text/javascript"><![CDATA[
    function parseSVG(s) {
        var div= document.createElementNS('', 'div');
        div.innerHTML= '<svg xmlns="">'+s+'</svg>';
        var frag= document.createDocumentFragment();
        while (div.firstChild.firstChild)
        return frag;

        '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'

**: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.

Solution 2

The accepted answer shows too complicated way. As Forresto claims in his answer, "it does seem to add them in the DOM explorer, but not on the screen" and the reason for this is different namespaces for html and svg.

The easiest workaround is to "refresh" whole svg. After appending circle (or other elements), use this:


This does the trick. The circle is on the screen.

Or if you want, use a container div:


And wrap your svg inside container div:

<div id="cont">
    <svg xmlns:svg="" xmlns="" viewBox="0 0 200 100" width="200px" height="100px">

The functional example:

The advantages of this technique:

  • you can edit existing svg (that is already in DOM), eg. created using Raphael or like in your example "hard coded" without scripting.
  • you can add complex element structures as strings eg. $('svg').prepend('<defs><marker></marker><mask></mask></defs>'); like you do in jQuery.
  • after the elements are appended and made visible on the screen using $("#cont").html($("#cont").html()); their attributes can be edited using jQuery.


The above technique works with "hard coded" or DOM manipulated ( = document.createElementNS etc.) SVG only. If Raphael is used for creating elements, (according to my tests) the linking between Raphael objects and SVG DOM is broken if $("#cont").html($("#cont").html()); is used. The workaround to this is not to use $("#cont").html($("#cont").html()); at all and instead of it use dummy SVG document.

This dummy SVG is first a textual representation of SVG document and contains only elements that are needed. If we want eg. to add a filter element to Raphael document, the dummy could be something like <svg id="dummy" style="display:none"><defs><filter><!-- Filter definitons --></filter></defs></svg>. The textual representation is first converted to DOM using jQuery's $("body").append() method. And when the (filter) element is in DOM, it can be queried using standard jQuery methods and appended to the main SVG document which is created by Raphael.

Why this dummy is needed? Why not to add a filter element strictly to Raphael created document? If you try it using eg. $("svg").append("<circle ... />"), it is created as html element and nothing is on screen as described in answers. But if the whole SVG document is appended, then the browser handles automatically the namespace conversion of all the elements in SVG document.

An example enlighten the technique:

// Add Raphael SVG document to container element
var p = Raphael("cont", 200, 200);
// Add id for easy access
// Textual representation of element(s) to be added
var f = '<filter id="myfilter"><!-- filter definitions --></filter>';

// Create dummy svg with filter definition 
$("body").append('<svg id="dummy" style="display:none"><defs>' + f + '</defs></svg>');
// Append filter definition to Raphael created svg
$("#p defs").append($("#dummy filter"));
// Remove dummy

// Now we can create Raphael objects and add filters to them:
var r = p.rect(10,10,100,100);

Full working demo of this technique is here:

( I have (yet) no idea, why $("#cont").html($("#cont").html()); doesn't work when using Raphael. It would be very short hack. )

Solution 3

The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.


<svg xmlns=""></svg>


var circle ="svg").append("circle")
    .attr("r", "10")
    .attr("style", "fill:white;stroke:black;stroke-width:5");

Solution 4

JQuery can't append elements to <svg> (it does seem to add them in the DOM explorer, but not on the screen).

One workaround is to append an <svg> with all of the elements that you need to the page, and then modify the attributes of the elements using .attr().

  .append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
  .mousemove( function (e) {
          cx: e.pageX,
          cy: e.pageY

Solution 5

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:

var svg = document.createElementNS('', 'svg'),
    circle = document.createElementNS('', 'circle');

var $circle = $(circle).attr({ //All your attributes });


The only down side is that you have to create each SVG element with the right namespace individually or it won't work.

Solution 6

Found an easy way which works with all browsers I have (Chrome 49, Edge 25, Firefox 44, IE11, Safari 5 [Win], Safari 8 (MacOS)) :

// Clean svg content (if you want to update the svg's objects)
// Note : .html('') doesn't works for svg in some browsers
// add some objects
$('#svgObject').append('<polygon class="svgStyle" points="10,10 50,10 50,50 10,50 10,10" />');
$('#svgObject').append('<circle class="svgStyle" cx="100" cy="30" r="25"/>');

// Magic happens here: refresh DOM (you must refresh svg's parent for Edge/IE and Safari)
<script src=""></script>

<div id="svgContainer">
  <svg id="svgObject" height="100" width="200"></svg>

<span>It works if two shapes (one square and one circle) are displayed above.</span>

Solution 7

I can see circle in firefox, doing 2 things:

1) Renaming file from html to xhtml

2) Change script to

<script type="text/javascript">
    var obj = document.createElementNS("", "circle");
    obj.setAttributeNS(null, "cx", 100);
    obj.setAttributeNS(null, "cy", 50);
    obj.setAttributeNS(null, "r",  40);
    obj.setAttributeNS(null, "stroke", "black");
    obj.setAttributeNS(null, "stroke-width", 2);
    obj.setAttributeNS(null, "fill", "red");

Solution 8

Based on @chris-dolphin 's answer but using helper function:

// Creates svg element, returned as jQuery object
function $s(elem) {
  return $(document.createElementNS('', elem));

var $svg = $s("svg");
var $circle = $s("circle").attr({...});

Solution 9

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.

var xml = jQuery.parseXML('<circle xmlns="" cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');

Solution 10

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:

    Pablo("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');

You can also create SVG elements on the fly, without specifying markup:

var circle ={

Solution 11

I would suggest it might be better to use ajax and load the svg element from another page.

$('.container').load(href + ' .svg_element');

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:


Solution 12

This is working for me today with FF 57:

function () {
    // JQuery, today, doesn't play well with adding SVG elements - tricks required
    $(selector_to_node_in_svg_doc).text("New").attr("x", "340").text("New")
        .attr('stroke', 'blue').attr("style", "text-decoration: line-through");


Solution 13

 var svg; // if you have variable declared and not assigned value.
 // then you make a mistake by appending elements to that before creating element    
 // at some point you assign to svg
 svg = document.createElementNS('', "svg")
 // then you put it in DOM
 // it wont render unless you manually change myDiv DOM with DevTools

// to fix assign before you append
var svg = createElement("svg", [
    ["version", "1.2"],
    ["xmlns:xlink", ""],
    ["aria-labelledby", "title"],
    ["role", "img"],
    ["class", "graph"]
function createElement(tag, attributeArr) {
      // .createElementNS  NS is must! Does not draw without
      let elem = document.createElementNS('', tag);             
      attributeArr.forEach(element => elem.setAttribute(element[0], element[1]));
      return elem;
// extra: <circle> for example requires attributes to render. Check if missing.

Solution 14

I have made a small function for that. As for jQuery append method, the problem is the requirement for specifying namespace for SVG which is "" More

So what if I prepare it for append method? In that case the only thing you need to offer is some parameters like:

tagName: It can be every SVG element like rect, circle, text, g etc.

text: If you are using something like text tagname, you'll need to specify text

And other known attributes for an SVG elements.

Thus what I'm going to do is defining a function named createSvgElem() which uses document.createElementNS() internally.

Here is an example:

   createSvgElem({tagName: "text", x: 10, y: 10, text: "ABC", style: "fill: red"})

And here's the function:

   function createSvgElem(options){
        var settings = $.extend({
            }, options);

            var el = document.createElementNS('', settings.tagName);
            for (var k in settings)
                if(k != "tagName" && k != "text" && settings[k] != "")//If attribute has value
                    el.setAttribute(k, settings[k]);

            if ("text" in settings)
                el.textContent = settings.text; //el.innerText; For IE
            return el;

Here you can try it yourself:

Solution 15

With jquery you can do just that. setting the DataType to 'text'.

    url: "url-to-svg.svg",
    dataType : 'text'
.done(function(svg) { 
    let svg_live = $(svg);
    svg_live.append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');

Solution 16

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.