Arihant Arihant - 5 months ago 10
Javascript Question

How to add to <SVG> element from array

I have an array with

<SVG>
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="http://www.w3.org/2000/svg"
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>' ]


Appending
[1]


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
[2]


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


This gives DOM Exception error.

Answer

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: https://jsfiddle.net/LukaszWiktor/wd3w2rjL/