I am trying to programmatically create inline svg images of a row of shields.
My shield is a simple path:
<path fill="red" d="M0 0 L0 15 q0 25 20 35 q20 -10 20 -35 L40 0z"></path>
Here is my script:
const element = document.querySelector('main')
for (let i = 0; i < 10; ++i) {
element.appendChild(document.createElementNS('http:http://www.w3.org/2000/svg', 'svg'))
element.lastChild.setAttribute('width', 400)
element.lastChild.setAttribute('height', 400)
// Code to add path inside svg, removed it and still didn't work
element.lastChild.appendChild(document.createElementNS('http:http://www.w3.org/2000/svg', 'path'))
element.lastChild.lastChild.setAttribute('fill', 'red')
element.lastChild.lastChild.setAttribute('d', 'M0 0 L0 15 q0 25 20 35 q20 -10 20 -35 L40 0z')
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
main {
display: flex;
}
svg {
background-color: blue;
}
</style>
<main>
<svg>
<path fill="red" d="M0 0 L0 15 q0 25 20 35 q20 -10 20 -35 L40 0z"></path>
</svg>
</main>
</body>
</html>
Copyable code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
main {
display: flex;
}
svg {
background-color: blue;
}
</style>
<main>
<svg>
<path fill="red" d="M0 0 L0 15 q0 25 20 35 q20 -10 20 -35 L40 0z"></path>
</svg>
</main>
<script>
const element = document.querySelector('main')
for(let i = 0; i < 10; ++i) {
element.appendChild(document.createElementNS('http:http://www.w3.org/2000/svg', 'svg'))
element.lastChild.setAttribute('width', 400)
element.lastChild.setAttribute('height', 400)
// Code to add path inside svg, removed it and still didn't work
element.lastChild.appendChild(document.createElementNS('http:http://www.w3.org/2000/svg', 'path'))
element.lastChild.lastChild.setAttribute('fill', 'red')
element.lastChild.lastChild.setAttribute('d', 'M0 0 L0 15 q0 25 20 35 q20 -10 20 -35 L40 0z')
}
</script>
</body>
</html>
The first svg is being properly rendered, but my auto generated svgs are not being rendered.
How do I programmatically create inline svg images of a row of shields?
Thanks in advance!
I've looked at:
- JavaScript inline SVG not rendering [duplicate]: The answer given is to use
createElementNS
, which I'm already using. - Inline-SVG not rendering when generated by JS: Answer talks about external svg.
- Inline SVG in CSS: Answers talk about data uris to embed SVG. Not what I'm doing.
- img src SVG changing the styles with CSS: Answers talk about external svgs.