Arihant Arihant - 2 years ago 77
Javascript Question

How to add to <SVG> element from array

I have an array with

element code. How can I append to that using JavaScript. I tried the following:

Example Array:

global_array[0] = [ '<svg data="BusinessProductFigure" x="553.671875"
y="167" id= "something" xmlns=""
version="1.1"><rect x="4" y="4" width="60" height="14"
fill="rgb(299,299,162)" stroke-linejoin="round"
stroke="rgb(299,299,162)" stroke-width="1"/></svg>' ]


for(var i = 0; i <= global_array.length; i++) {
document.getElementById("main_svg").innerHTML = global_array[i];

Gives no error but nothing is appended. Checked in console.

Appending test

for(var i = 0; i <= global_array.length; i++) {"#main_svg").append(global_array[i]);

This gives DOM Exception error.

Answer Source

Your first approach will almost work if you change the loop end condition from i<=global_array.length to i<global_array.length. I say almost because it will work only for the last element in the array. Setting innerHTML doesn't append an element - it replaces all content. Another requirement is that the container ("#main_svg") cannot be an <svg> tag. You cannot nest <svg>s

Almost working example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download