Reputation: 1703
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?
Upvotes: 1
Views: 2078
Reputation: 101820
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);
}
Upvotes: 5