DocumentFragment: getElementById() 方法

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有瀏覽器中可用。

DocumentFragmentgetElementById() 方法返回一個 Element 物件,該物件表示其 id 屬性與指定字串匹配的元素。由於元素 ID 如果指定了,必須是唯一的,因此它們是快速訪問特定元素的有用方式。

如果您需要訪問沒有 ID 的元素,可以使用 querySelector() 使用任何 選擇器 來查詢元素。

注意: 文件片段中的 ID 應該是唯一的。如果文件片段中的兩個或多個元素具有相同的 ID,此方法將返回找到的第一個元素。

語法

js
getElementById(id)

注意: 此方法名稱中 "Id" 的大小寫必須正確才能使程式碼正常工作;getElementByID()無效的,並且不會起作用,無論它看起來多麼自然。

引數

id

要定位的元素的 ID。ID 是一個區分大小寫的字串,在文件片段內是唯一的:任何給定的 ID 應該只有一個元素。

返回值

一個 Element 物件,描述與指定 ID 匹配的 DOM 元素物件,如果文件片段中未找到匹配的元素,則為 null

示例

擴充套件元素列表

在此示例中,文件包含一個帶有單個專案 Cherry 的列表。我們還建立一個包含另外四個專案 AppleOrangeBananaMelon 的文件片段。

然後,我們在文件和片段中記錄使用 getElementById() 查詢 AppleCherry 的結果。此時,Cherry 只出現在文件中,而 Apple 只出現在片段中。

如果單擊“將片段新增到文件”,我們會將片段附加到文件內的列表,然後再次記錄在文件和片段中查詢 AppleCherry 的結果。這次,AppleCherry 都出現在文件中,而兩者都不出現在片段中。

這是因為將片段附加到文件會將其節點移入 DOM,從而留下一個空的 DocumentFragment

HTML

html
<button id="add">Add fragment to document</button>
<button id="reset">Reset example</button> <br />
List content:
<ul>
  <li id="Cherry">Cherry</li>
</ul>
Fragment content:
<ul id="fragment"></ul>
Current status:
<pre id="log"></pre>

JavaScript

js
// Create the document fragment with its initial content
const fragment = new DocumentFragment();
["Apple", "Orange", "Banana", "Melon"].forEach((fruit) => {
  const li = document.createElement("li");
  li.textContent = fruit;
  li.id = fruit;
  fragment.append(li);
});

// When the button is clicked, add the fragment to the list
document.getElementById("add").addEventListener("click", () => {
  document.querySelector("ul").append(fragment);
  displayStatus();
});

// Log the results of both getElementById()
function displayStatus() {
  const log = document.getElementById("log");
  log.textContent = "";
  ["Apple", "Cherry"].forEach((id) => {
    log.textContent += `document.getElementById("${id}") ${
      document.getElementById(id) ? "Yes" : "No"
    }\n`;
    log.textContent += `fragment.getElementById("${id}") ${
      fragment.getElementById(id) ? "Yes" : "No"
    }\n`;
  });

  // Empty the fragment viewer and fill it with the current content
  const fragmentViewer = document.getElementById("fragment");
  while (fragmentViewer.hasChildNodes()) {
    fragmentViewer.removeChild(fragmentViewer.lastChild);
  }
  for (entry of fragment.children) {
    fragmentViewer.appendChild(entry.cloneNode(true));
  }
}

// Log the initial state
displayStatus();

// Hook the reset button
document.getElementById("reset").addEventListener("click", () => {
  document.location.reload();
});

結果

規範

規範
DOM
# dom-nonelementparentnode-getelementbyid

瀏覽器相容性

另見