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

浏览器兼容性

另见