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

瀏覽器相容性