使用javascript将路径附加到SVG
我试图使用javascript将path元素附加到一些内联svg中,但我得到了一个错误:“Uncaught NotFoundError:试图在不存在节点的上下文中引用该节点” 有人能解释为什么这个javascript不能与我的HTML一起使用吗使用javascript将路径附加到SVG,javascript,svg,appendchild,Javascript,Svg,Appendchild,我试图使用javascript将path元素附加到一些内联svg中,但我得到了一个错误:“Uncaught NotFoundError:试图在不存在节点的上下文中引用该节点” 有人能解释为什么这个javascript不能与我的HTML一起使用吗 <body> <svg height='500' width='500'></svg> <script> var svg = document.getElementsB
<body>
<svg height='500' width='500'></svg>
<script>
var svg = document.getElementsByTagName("svg")[0];
var pathElement = svg.appendChild("path");
</script>
</body>
var svg=document.getElementsByTagName(“svg”)[0];
var pathElement=svg.appendChild(“路径”);
appendChild接受一个元素而不是字符串,所以您需要的是这样的东西
var svg = document.getElementsByTagName("svg")[0];
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
// Use path.setAttribute("<attr>", "<value>"); to set any attributes you want
var pathElement = svg.appendChild(path);
var svg=document.getElementsByTagName(“svg”)[0];
var path=document.createElements(“http://www.w3.org/2000/svg“,”路径“);
//使用path.setAttribute(“,”);设置所需的任何属性
var pathElement=svg.appendChild(路径);
任何路过并希望看到其运行的人的工作示例:
HTML
<svg id="mysvg" width="100" height="100">
<circle class="c" cx="50" cy="50" r="40" fill="#fc0" />
</svg>
var mysvg = document.getElementById("mysvg");
//uncomment for example of changing existing svg element attributes
/*
var mycircle = document.getElementsByClassName("c")[0];
mycircle.setAttributeNS(null,"fill","#96f");
*/
var svgns = "http://www.w3.org/2000/svg";
var shape = document.createElementNS(svgns, "rect");
shape.setAttributeNS(null,"width",50);
shape.setAttributeNS(null,"height",80);
shape.setAttributeNS(null,"fill","#f00");
mysvg.appendChild(shape);