XML technologies / SVG / Interactive graphics / Creating elements dynamically / Removing elements again

(Excerpt from “Das Einsteigerseminar SVG — Webgrafiken mit XML” by Helma Spona)

When the user clicks a bar’s text a second time, remove the previously created elements before creating new ones. Each function call therefore stores the clicked group’s name in the variable status. Initially, this variable contains "", an empty string. If it contains another value, a conditional branch removes the group’s contents except its original elements. To avoid removing too much, the original element count must be known. The script uses the variable anzahlAnf to store that count before creating child elements. Query it afterward, but remove the old elements before creating new ones. To remove an element, first retrieve it into a variable and pass that variable to the removeChild method.

if (status!="")
{
  //alte Einträge löschen
  elem01=svgdok.getElementById(status);
  anzahl=elem01.getChildNodes().getLength();
  for (i=anzahl-1;i>=anzahlAnf;i--)
  {
    elem01.removeChild(elem01.getChildNodes(i));
  }
}

Note:
Removing multiple elements from a group or other parent tag changes the indices of subsequent elements. Start with the highest index, removing the last element first. Here, the loop runs from anzahl-1 to anzahlAnf, reducing the counter i with i-- instead of increasing it.

   

 

 

 

back to top