javascript - 尝试访问 SVG 元素时 getElementById 返回 null

标签 javascript html dom getelementbyid

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

<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>

我希望显示一个青色方 block 。但是,我收到错误“无法读取 null 的属性 setAttribute”。

我可以做什么来解决这个问题?

最佳答案

当您创建 svg 元素时,您已经在分配的变量中引用了它。无需再次从文档中获取。这甚至是不可能的,因为它尚未添加到文档中。这是更正后的代码:

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);

关于javascript - 尝试访问 SVG 元素时 getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56386573/

相关文章:

javascript - 如何计算 JavaScript 测验的百分比分数?

javascript - 加速 Gatsby 性能

javascript - JavaScript 的三元运算符的运算符优先级

javascript - IE7和IE8下拉框中不显示更大的内容

javascript - 我需要一个工作示例来使用 JavaScript 的 youtube Data API 3 检索公共(public) youtube 播放列表

html - 100% 高度 div,由于 margin-top 50px,滚动条离开屏幕 50px。自动溢出

html - 阿拉伯字符和拉丁字符混淆

javascript - HTML5 内容可编辑触发器开/关

javascript - 如何查询自定义 HTML 元素?

php - 使用 PHP DOM 更改 CSS