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?
Asked
Active
Viewed 1,757 times
1
-
Possible duplicate of [How to use z-index in svg elements?](http://stackoverflow.com/questions/17786618/how-to-use-z-index-in-svg-elements) – zero298 Jan 25 '16 at 23:56
-
no I know that solution. I just want to know more effective way – tprieboj Jan 25 '16 at 23:57
-
1What are you doing currently? – Twisty Jan 25 '16 at 23:57
-
what I wrote ... delete svg element and append it again on svg field – tprieboj Jan 26 '16 at 00:02
-
did you check [How do I manipulate the SVG DOM and create elements?](http://stackoverflow.com/questions/8320002/how-do-i-manipulate-the-svg-dom-and-create-elements) – Artem Jan 26 '16 at 00:03
1 Answers
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
-
-
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