I have an SVG on the page which I am trying to edit. When I look at the element in the console after making the changes, I can see the source looks correct. Yet, it doesn’t upgrade in the browser. I’m suspecting this is some sort of caching issue? Otherwise I’m missing something basic. Here is the example:
<div class="svg">
<svg id="svg" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 40" style="background-color: #333;">
<line x1="10" x2="40" y1="40" y2="10" stroke="red"></line>
</svg>
</div>
<script>
const svg = document.getElementById('svg');
const svgNS = svg.getAttribute('xmlns');
const line = document.createElementNS(svgNS, 'line');
line.setAttributeNS(svgNS, 'x1', '10');
line.setAttributeNS(svgNS, 'x2', '40');
line.setAttributeNS(svgNS, 'y1', '10');
line.setAttributeNS(svgNS, 'y2', '40');
line.setAttributeNS(svgNS, 'stroke', 'red');
svg.appendChild(line);
console.log(svg);
</script>
Very simply, the SVG comes up with one red slash and I’m trying to dynamically turn it into an X by adding a slash in the other direction. When I look in the console, I see this:
<svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40" style="background-color: #333;">
<line x1="10" x2="40" y1="40" y2="10" stroke="red"></line>
<line x1="10" x2="40" y1="10" y2="40" stroke="red"></line>
</svg>
Yet the browser continues to just show the one slash. Most of the other similar questions have answers that say to specify the namespace when editing. I’m doing this. What am i missing?
2
There is no need to set the namespace when setting an attribute. Use line.setAttribute(...
or line.setAttributeNS(null...
instead.
<div class="svg">
<svg id="svg" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 40" style="background-color: #333;">
<line x1="10" x2="40" y1="40" y2="10" stroke="red"></line>
</svg>
</div>
<script>
const svg = document.getElementById('svg');
const svgNS = svg.getAttribute('xmlns');
const line = document.createElementNS(svgNS, 'line');
line.setAttribute('x1', '10');
line.setAttribute('x2', '40');
line.setAttribute('y1', '10');
line.setAttribute('y2', '40');
line.setAttribute('stroke', 'red');
svg.appendChild(line);
console.log(svg);
</script>