Simple SVG manipulation with jQuery

Okay, so I wanted to do something ‘simple’. I just wanted to load in an SVG document into a webpage, and then add bits to it.

Loading the SVG is easy. To make things even easier, with modern browsers I can just drop the SVG code in-line into my document and it works. For this project I don’t care too much about it not rendering on legacy browsers; The UI will fall-back gracefully without the SVG there.

There are a myriad of SVG javascript libraries out there from the “seems legit but merely doesn’t do what I want” to the “were you drinking furniture polish when you thought that was a good idea?!”, to the “it’s really elegant and tiny honest, here’s just the page of boiler-plate and flash code you need to draw the `Hello world’ page”.

Looking across the different options, I spent hours trying to find something that would do what I wanted in a reasonably straight-forward way, and eventually gave up and figured I’d have to do it myself. By “myself” I mean cheat and use jQuery, because it makes writing javascript for me less of a masochistic endeavour.

So first, I’m going to start with some boilerplate code. I’m not claiming this is the best in the universe, but it’s basically “load jquery. chuck some SVG on the page”:

<head> <title>Simple SVG example</title> </head>

<div><svg xmlns="" version="1.1" id="mySVG">
  <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="aquamarine"/>


Great. It draws a circle. 

Now I’ve given the svg element an id of mySVG, so using jQuery to add extra elements to the drawing is easy. The only problem is that the elements it has have to be in the ”” namespace, and as far as I’m aware, jQuery doesn’t let you add a namespace when creating a new element.

It’s pretty easy to work around. I just use document.createElementNS() to make the element with the correct namespace, and then be slack and use jQuery to do the rest.

He’s some code I’m using to do just that. It’s a bit more abstracted than for a simple example, mainly because I’m going to be adding more than one or two items:

<html> <head><title>Simple SVG example</title> <script type="text/javascript" src=""></script> <script type="text/javascript"> function a(element,eldict) { el = $(document.createElementNS('', element)); el.attr(eldict).appendTo('#mySVG'); } $(function(){ a('circle', {cx: 80, cy:80, r:44, stroke:'#0000ff', fill:'none'}); a('circle', {cx: 180, cy:110, r:10}); }); </script> </head> <body> <div><svg xmlns="" version="1.1" id="mySVG"> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="aquamarine"/> </svg></div> </body></html>


  1. not-on posted this