jquery's append not working with svg element?

jquery examples
jquery link
jquery meaning
jquery w3schools
jquery cdn
jquery documentation
jquery ui
jquery selector

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?

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 SVGElement—it 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="http://www.w3.org/1999/xhtml"><head>
</head><body>
    <svg id="s" xmlns="http://www.w3.org/2000/svg"/>
    <script type="text/javascript">
        function makeSVG(tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', 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'});
        document.getElementById('s').appendChild(circle);
        circle.onmousedown= function() {
            alert('hello');
        };
    </script>
</body></html>

*: 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('http://www.w3.org/1999/xhtml', 'div');
        div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
        var frag= document.createDocumentFragment();
        while (div.firstChild.firstChild)
            frag.appendChild(div.firstChild.firstChild);
        return frag;
    }

    document.getElementById('s').appendChild(parseSVG(
        '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
    ));
]]></script>

**: 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.

jQuery API Documentation, takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code. What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

jQuery Tutorial, is not a necessity because Javascript browser support is more consistent than ever. jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming. jQuery is easy to learn. With our online editor, you can edit the code, and click on a button to view the result. Click on the "Try it Yourself" button to see how it works. Start learning jQuery now! Use the correct selector to hide all <p> elements.

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.

HTML

<svg xmlns="http://www.w3.org/2000/svg"></svg>

Javascript

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

jQuery Introduction, . Meanwhile, AJAX is a method to immediately update parts of the UI without reloading the web pages. The purpose of jQuery is to make it much easier to use JavaScript on your website. If you want to study these subjects first, find the tutorials on our Home page. jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website.

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().

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

http://jsfiddle.net/8FBjb/1/

Is jQuery going to die in 2019?, The jQuery library contains the following features: HTML/DOM manipulation; CSS manipulation; HTML event methods; Effects and animations; AJAX; Utilities. Tip:  jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License.

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('http://www.w3.org/2000/svg', 'svg'),
    circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');

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

$(svg).append($circle);

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

Is jquery a javascript library or framework?, jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly  jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. If you're new to jQuery, we recommend that you check out the jQuery Learning Center.

JavaScript, JQuery, Ajax: Are They The Same Or Different? -, jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly  Users. There's a lot more to learn about building web sites and applications with jQuery than can fit in API documentation. If you're looking for explanations of the basics, workarounds for common problems, best practices, and how-tos, you're in the right place!

jQuery UI, To build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. Earlier versions might work, but are not supported. For Windows, you have to  jQuery Color SVG Color Names 2.1.2 - uncompressed, minified. jQuery Color With Names (last two together) 2.1.2 - uncompressed, minified. Showing the latest stable release for QUnit. See all versions of QUnit . QUnit 2.9.2 - uncompressed , theme. Showing the latest stable release for PEP. See all versions of PEP .

jQuery UI Demos, The jQuery Foundation is now the JS Foundation. For more information about our expanded vision to become the center of gravity for the entire JavaScript  jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.

Comments
  • This answer is still relevant! I just had a bizarre bug where added elements show in the Chrome element inspector, but would not render. If I RMB>edit as html on the html tag and hit enter everything displays (but all event listeners vanish). After reading this answer I changed my createElement calls to createElementNS and now everything works!
  • You can manipulate the SVG elements with jquery once they are created using the DOM method createElementNS. You can change the makeSVG function to 'return $(el)' and now you have a svg element that can use jquery methods.
  • Ah! So that's why it won't work. I tried the exact same thing with two different libraries, one in jQuery and one in D3.js. I got exactly the same source output in HTML using both, but the jQuery-generated elements would not render while the D3-generated ones did! I recommend using D3: d3.select('body').append('svg').attr('width','100%');
  • @MadsSkjern: DOM Level 3 LS never made it to browsers. The originally-Mozilla-only DOMParser is now more widely supported, though, and jQuery has $.parseXML.
  • It's still relevant. bobince hates the mess of HTML5, I hate the mess of the whole web, because nowhere you can find good code without hacks because of that mess. WWW should be renamed to WWM World Wide Mess.
  • I am using my (Home made) solution for handling SVG and have the same Problem as Raphael, when using the "reparsing trick" with $(#picture).html ..., but my solution was to re-init some cached SVG elements (marking rectangle, transformataion and so on)
  • You are a wizard. I was looking at the accepted answer and I was like man this is gonna be a pain. Then, I saw this and it does everything I need it to in one short line. Thank you!
  • THIS WAS CAUSING ME TO LOSE MY MARBLES... thought I could magically use js DOM elms on the SVG namespace like one might think... got the tag inspector to recognize the insertions... but not dice till now!
  • Worked great for me when appending my existing polygon and path tags to a newly created parent svg tag. Thanks!
  • $("#cont").html($("#cont").html()); worked great in Chrome, but didn't work in IE 11 for me.