I was trying to create SVG elements in JS and append them to a “rect” element. That doesn’t work, but I can append to a “g” element. I get the feeling I’m violating some rule, but I can’t find anything that says it shouldn’t work.
if you look at my code sample, you’ll see that r2 is shown, but r1 is missing.
<html>
<body>
<div>
<svg height=100vh width=100%>
<g id='g'>
<rect id='r' width=100 height=100 fill='green'/>
</g>
</svg>
</div>
<script>
function setAttribs(elem, attrs) {
Object.entries(attrs).forEach(([key, value]) => {
elem.setAttribute(key, value);
});
return elem;
};
const g = document.getElementById('g');
const r = document.getElementById('r');
const r1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
const r2 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
setAttribs(r1, {
x: 0,
y: 100,
height: 50,
width: 40,
fill: 'blue'
});
setAttribs(r2, {
x: 0,
y: 150,
height: 50,
width: 40,
fill: 'red'
});
r.appendChild(r1);
g.appendChild(r2);
</script>
</body>
</html>