0

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.

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
Arihant
  • 3,847
  • 16
  • 55
  • 86
  • 1
    Possible duplicate of [D3 append (insert) existing SVG string (or element) to a DIV](http://stackoverflow.com/questions/29855452/d3-append-insert-existing-svg-string-or-element-to-a-div) – ssc-hrep3 Jun 15 '16 at 20:00
  • Your example array is assigning a sub-array to element zero of `global_array`. Is this correct? – Bo Borgerson Jun 15 '16 at 20:03

2 Answers2

1

here I could see in the first line..

change global_array[0] to global_array

or

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>';

this will work as per your code :)

Brajendra Swain
  • 355
  • 2
  • 8
1

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/

Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82