Not Working Example:
const svg = document.createElement('svg')
svg.setAttribute('height', '100')
svg.setAttribute('width', '100')
document.body.appendChild(svg)
const rect = document.createElement('rect')
rect.setAttribute('height', '100%')
rect.setAttribute('width', '100%')
rect.setAttribute('fill', 'red')
svg.appendChild(rect)
Working Example:
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
svg.setAttribute('height', '100')
svg.setAttribute('width', '100')
document.body.appendChild(svg)
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
rect.setAttribute('height', '100%')
rect.setAttribute('width', '100%')
rect.setAttribute('fill', 'red')
svg.appendChild(rect)
Seems I have to specify the namespace each time I create an svg
tag or any of its descendants via JS.
Question 1: Why is this necessary? According to MDN docs on the svg
tag:
Note: The
xmlns
attribute is only required on the outermost svg element of SVG documents. It is unnecessary for inner svg elements or inside HTML documents.
I'm nesting the svg
inside HTML here, so the xmlns
attribute shouldn't be needed, right?
Question 2: Is there a way to avoid this repetition?
Having to type
document.createElementNS('http://www.w3.org/2000/svg', 'rect')
every time is tedious.
Is there a shorter method available?