Moving SVG elements in Z

3 Jul 2011 Code on Github


This a quick post which isn't directly about making SVGs interactive, but could be useful for an interactive SVG. It was prompted by a question of Stack Overflow about how to move one element drawn after another below it.

Because of the way SVG works, sequentially drawing elements on the page in the order they are in the file, there is no simple way to do this. Instead you have to play with the DOM, grabbing the element you want to bury and inserting it into the beginning of the document.

The code

In the following SVG, a group of two lines is drawn after two circles, but moved in front of them with a short bit of Javascript.

<svg viewBox="0 0 200 200" xmlns="">
    <circle cx="80" cy="80" r="40" fill="blue"/>
    <circle cx="120" cy="120" r="40" fill="green"/>

    <g id="line-group" stroke-width="2" stroke="black">
        <line x1="0" y1="10" x2="190" y2="200" />
        <line x1="10" y1="0" x2="200" y2="190" />

    <script type="text/javascript"><![CDATA[
        var svg = document.getElementsByTagName("svg")[0];
        var line_group = document.getElementById("line-group");
        svg.insertBefore(line_group, svg.firstChild);

Despite the line group being after the after the circles, the lines should be drawn below the circles. In somes cases, such as the thumbnail generated by my computer, or if you open the SVG in Inkscape, the script isn't called and the lines are drawn on top of the circles.

All the work is done in lines 12 and 13. Line 12 grabs the group of lines, line 13 inserts it into the svg before all the other elements.

Comments (2)

Charlie Childs on 9 Oct 2018, 2:31 p.m.

I have implemented, successfully some of your code to get SVG Tooltips working - Brilliant.
These tooltips are read from a MYSQL database and so are different for each item hovered.

One of my resultant issues is that the tooltip disappears under an adjacent SVG element if it is close, which it has to be as part of the application.

I wonder if there is any way of making the tooltip always display above all other SVG elements in a manner similar to your "Moving SVG elements in Z" article above.

Any help appreciated.

Peter on 9 Oct 2018, 9:53 p.m.

The easiest way is to just put the tooltip at the bottom of the SVG document, so it's drawn last. If that's not possible then (if elements are added dynamically to the SVG maybe), the you could use parent.removeChild(tooltip); to remove the tooltip element from the the SVG (the parent would probably be the SVG document itself). Then use document.appendChild(tooltip); to add it to the end of the SVG.