Change Drawing Order

SVG elements are rendered via the painter's algorithm, i.e. subsequent elements are painted on top of previously painted elements. There were several discussions about the z-index attribute, that would control explicitly , which element would be in front of another one. There seems to be a good chance, that this attribute will be introduced in a later version of SVG.

Meanwhile the only way to change the drawing order is to change the elements position in the DOM.

circle in front of line line in front of circle

The implementation uses the method replaceChild of the DOM's Node object.

   function swap(parent, elem1, elem2)
   {
      var tmp = elem1.cloneNode(true);
      parent.replaceChild(tmp, elem2);
      parent.replaceChild(elem2, elem1);
   }
This solution requires, that both elements are childs of the same parent. Also note, that any assigned event listeners will get lost, when cloneNode is applied.


© 2000 MecXpert