You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用document.createElement创建SVG path元素不显示该如何解决?

问题原因

SVG 是基于 XML 的图形格式,所有 SVG 元素都属于独立的 SVG 命名空间,使用普通的 document.createElement() 方法创建的是 HTML 命名空间下的 DOM 元素,浏览器不会将其识别为合法的 SVG 元素,因此即使属性设置正确、审查元素能看到标签,也不会正常渲染。

解决方法

创建 SVG 元素时需要使用 document.createElementNS() 方法,显式指定 SVG 命名空间为 http://www.w3.org/2000/svg,修正后的 JS 代码如下:

const svg = document.querySelector( `svg` ),
      // 替换普通createElement,指定SVG命名空间创建元素
      path = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );

path.setAttribute(
  `d`,
  `
   M10 50
   C20 30, 40 30, 50 50
   C60 70, 80 70, 90 50  
  `
)

svg.appendChild( path );

修改后 path 元素即可正常渲染显示。


内容的提问来源于stack exchange,提问作者Lynel Hudson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 08:48:03