首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试访问SVG元素时,getElementById返回null

尝试访问SVG元素时,getElementById返回null
EN

Stack Overflow用户
提问于 2019-05-31 06:47:50
回答 1查看 173关注 0票数 0

我正在尝试编写一个脚本,它将动态创建一个SVG元素并显示它。但是,当我设置SVG元素的ID,然后尝试使用Document.getElementById()访问它时,它返回null。我使用window.onload来确保在调用脚本之前已经加载了文档。

代码语言:javascript
复制
<body>
  <script>
  function buildSVG(color) {
  const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
  return shape;
}


function addSVG(color) {
  let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.id = "svgID";
  let elem = document.getElementById("svgID");
  elem.setAttribute('width', '600');
  svg.setAttribute('height', '250');
  svg.innerHTML = buildSVG(color);
  svg.setAttribute('style', 'border: 1px solid black');
  document.body.appendChild(svg);
}
  window.onload = addSVG("cyan");
  </script>
</body>

我希望显示一个青色的正方形。但是,我收到错误消息"cannot read property setAttribute of null“。

我能做些什么来解决这个问题呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-31 06:49:54

在创建svg-element时,在分配的变量中已经有了对它的引用。不需要再次从文档中获取它。这甚至是不可能的,因为它还没有添加到文档中。以下是更正后的代码:

代码语言:javascript
复制
function buildSVG(color) {
  const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
  return shape;
}


function addSVG(color) {
  let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.id = "svgID";
  svg.setAttribute('width', '600');
  svg.setAttribute('height', '250');
  svg.innerHTML = buildSVG(color);
  svg.setAttribute('style', 'border: 1px solid black');
  document.body.appendChild(svg);
}
window.onload = addSVG("cyan");

// after 1 second: get the svgID-element and change the border.
setTimeout(function(){
  document.getElementById('svgID').setAttribute('style', 'border: 1px dashed red');
}, 1000);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56386573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档