1

I want to make some svg elements to be on top . Something like Z-Index. I know that svg z-index is set by their draw order. I can change their order by deleting svg elem and redraw it again. So I am doing it "hard way" . Is there better way to do this using vanilla JS / JQuery?

tprieboj
  • 1,680
  • 6
  • 31
  • 54

1 Answers1

4

You don't need to delete the element and recreate it. You can just move it.

First, get a pointer to it, and its parent SVG:

var mysvg = document.getElementById("mysvg");
var myelement = document.getElementById("myelement");

Then use insertBefore() to insert it at the end. If you "insert" a node that is already part of the DOM, it gets moved instead.

mysvg.insertBefore(myelement, null);

Using null here means insert it as the last child.

Demo

function moveIt()
{
  var mysvg = document.getElementById("mysvg");
  var myelement = document.getElementById("myelement");

  mysvg.insertBefore(myelement, null);
}
<svg id="mysvg">
  <circle cx="100" cy="75" r="75" fill="green" id="myelement"/>
  <circle cx="200" cy="75" r="75" fill="red"/>
</svg>

<button onclick="moveIt()">Move it</button>

Update

The jQuery equivalent of the moveIt() function would be:

function moveIt()
{
  var mysvg = $("#mysvg");
  var myelement = $("#myelement");

  mysvg.append(myelement);
}
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
  • is there something similar in JQ? – tprieboj Jan 26 '16 at 14:55
  • Yes. I've updated the answer with the jQuery version of the `moveIt()` function. However please note that, in general, jQuery is not suitable for manipulating SVG elements. Many jQuery functions do not work with SVG. – Paul LeBeau Jan 26 '16 at 16:06