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

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

Create the elements by iterating over the appropriate array. This example uses a for-loop. For each array entry, create a rectangle, a text element with a link, and a horizontal line connecting child elements.

Note:
The variables ABSTAND, BREITE, HOEHE, hoehe and anfang are defined and initialized partly at script level and partly inside the function ausklappen, determining child elements’ gaps, sizes and positions.

First assign to the variable neuesElem a new rectangle created with the method createElement, passing the name of the <rect> tag. Then use the setAttribute method to set attributes, especially x and y. Calculate x as twice ABSTAND and y from the element height plus the gap. The method appendChild appends the new element to the parent stored in the variable elem. Create the horizontal line similarly by generating a <path> tag.

for (i=0;i<werte.length;i++)
{
  //Kasten
  neuesElem=svgdok.createElement("rect");  
  neuesElem.setAttribute("x",ABSTAND*2);
  neuesElem.setAttribute("y",hoehe+ABSTAND);
  neuesElem.setAttribute("width",BREITE);
  neuesElem.setAttribute("height",HOEHE);
  neuesElem.setAttribute("class","unterelement");
  neuesElem=elem.appendChild(neuesElem);
  //Linie waagerecht
  neuesElem=svgdok.createElement("path");
  neuesElem.setAttribute("d","M"+ABSTAND+" "+parseInt(hoehe+(HOEHE/2)+ABSTAND)+" h+"+ABSTAND);
  neuesElem.setAttribute("style","fill:none;stroke:black;stroke-width:1px");
  neuesElem=elem.appendChild(neuesElem);

To create text elements, first create an <a> tag for the hyperlink. Its attribute xlink:href cannot be set with the setAttribute method. Attributes using an XML namespace require the method setAttributeNS. Pass the namespace as a URL first. For the xlink namespace, use "http://www.w3.org/1999/xlink". The second parameter is the element, here href, followed by its value from the array links.

//Texte
neuesAElem=svgdok.createElement("a");
neuesAElem.setAttributeNS(

Then create the <text> element defining the link text. After setting attributes, use the method createTextNode to create the <text> tag’s contents. Append this content to the <text> element with appendChild, then insert the text element into the <a> tag, again using the appendChild( ) method. Finally, use the third appendChild( ) call to insert the <a> tag into the group. Calculate the new value of hoehe so the next element appears below.

  neuesElem=svgdok.createElement("text");  
  neuesElem.setAttribute("x",ABSTAND*2.5);
  neuesElem.setAttribute("y",hoehe+(ABSTAND*2.8));
  neuesElem.setAttribute("class","unterelement");
  neuesTElem=svgdok.createTextNode(werte[i]);
  neuesElem.appendChild(neuesTElem);
  neuesAElem.appendChild(neuesElem);
  elem.appendChild(neuesAElem);  
  hoehe=hoehe+ABSTAND+HOEHE;
  }
  //Linie vertikal
  ...
}

   

 

 

 

back to top