1

I'm trying to use JQuery to create an SVG element. The contents of the SVG is generated from a list of strings which is where I'm having my issues.

I'm populating a variable called 'arr' by looping through several hundred items in my database and creating an svg rect shaped based on that data which then gets appended to 'arr'. How can i append this list of string elements to my main SVG element in order to properly display it?

The main points here are:

  • Arr is populated with a list of strings, each one representing a shape to go inside the svg
  • The final Arr will be several hundreds strings

var mapSvg = $.parseHTML('<svg id="tile-map-svg" width="100%" height="300"></svg>');
arr = [
 '<rect height="50" width="50" fill="blue"/>',
  '<rect height="20" width="20" fill="green"/>'
]
mapSvg[0].append(arr);
$('#tile-map').append(mapSvg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<div style="background:lightblue; padding:10px;">
  <div id="tile-map">
  </div>
  <svg id='tile-map-svg' width="100" height="100">
      <rect height="25" width="25" fill="red" class="tile"/>
  </svg>
</div>

I also tried this and it didn't work either...

var mapSvg = $.parseHTML('<svg id="tile-map-svg" width="100%" height="600"></svg>');
arr = [
    '<rect height="50" width="50" fill="blue"/>',
  '<rect height="20" width="20" fill="green"/>'
]
for (var i = 0; i < arr.length; i++) {
    var el = $.parseHTML(arr[i])[0];
  mapSvg[0].append(el);
}
$('#tile-map').append(mapSvg);
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

2 Answers2

1

How about looping over all the elements in arr before parsing the html:

let html = '<svg id="tile-map-svg" width="100%" height="300">';
arr.forEach(shape => {
html += shape;
});
html += "</svg>";
const mapSvg = $.parseHTML(html);
$("#tile-map").append(mapSvg);
N8Javascript
  • 140
  • 10
0

Or simply copy HTML without jQ for example:

var mapSvg = document.getElementById("tile-map");
var arr = [
'<rect height="50" width="50" fill="blue"/>',
'<rect height="20" width="20" fill="green"/>'
]
var s = "<svg id='tile-map-svg' width=100 height=100>"+
arr.join('\n')+
"</svg>";
mapSvg.innerHTML = s;
mapSvg.innerHTML += s;
mapSvg.parentElement.innerHTML += mapSvg.outerHTML.replace(/</g,'&lt;').replace(/>/g,'&gt;');
<div style="background:lightblue; padding:10px;">
  <div id="tile-map">
  </div>
</div>
Jan
  • 2,178
  • 3
  • 14
  • 26