SVGSVGElement: getElementById() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

SVGSVGElement 接口的 getElementById() 方法会在 SVG 文档片段中(即搜索范围仅限于文档树的一个子集)搜索 id 属性与指定字符串匹配的 Element

语法

js
getElementById(id)

参数

id

要定位的元素的 ID。ID 是一个区分大小写的字符串,在 SVG 文档片段内是唯一的;每个 ID 应该只有一个元素与之对应。

返回值

一个 Element 对象,描述与指定 ID 匹配的 DOM 元素对象,如果 SVG 文档片段中未找到匹配的元素,则返回 null

示例

通过 ID 检索 Element

html
<svg
  id="exampleSVG"
  width="200"
  height="200"
  xmlns="http://www.w3.org/2000/svg">
  <circle id="circle1" cx="100" cy="100" r="50" fill="blue" />
</svg>
<button id="getElementButton">Get Element</button>
<p id="elementDisplay"></p>
js
const svgElement = document.getElementById("exampleSVG");
const getElementButton = document.getElementById("getElementButton");
const elementDisplay = document.getElementById("elementDisplay");

getElementButton.addEventListener("click", () => {
  const circleElement = svgElement.getElementById("circle1");
  if (circleElement) {
    elementDisplay.textContent = `Element found: ${circleElement.tagName}`;
  } else {
    elementDisplay.textContent = "Element not found.";
  }
});

规范

规范
Scalable Vector Graphics (SVG) 2
# __svg__SVGSVGElement__getElementById

浏览器兼容性