I was trying to manipulate SVG in plain JS and found that it won't behave as intended if I don't use methods like createElementNS
and setAttributeNS
.
<svg id="mydsvg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
The above markup works perfectly. But if you try to add another circle via the following code, you won't see it.
var circle = createElement('circle');
circle.setAttribute('cx', 50);
....
document.getElementById('mysvg').appendChild(circle);
But if you use createElementNS
and setAttributeNS
, it will work as expected.
To be worst, both createElement
and createElementNS
create identical DOM text.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…