文档:getElementById() 方法
Document 接口的 getElementById() 方法返回一个 Element 对象,该对象代表其 id 属性与指定字符串匹配的元素。由于元素 ID 在指定时必须是唯一的,因此它们是快速访问特定元素的有用方式。
如果需要访问没有 ID 的元素,可以使用 querySelector() 通过任何选择器查找元素。
注意: ID 在文档中应该是唯一的。如果文档中有两个或更多元素具有相同的 ID,此方法将返回找到的第一个元素。
语法
getElementById(id)
注意: 此方法名称中 "Id" 的大写必须正确,代码才能正常运行;getElementByID() 无效且无法工作,无论它看起来多么自然。
参数
id-
要定位的元素的 ID。ID 是一个区分大小写的字符串,在文档中是唯一的;只有一个元素应具有任何给定的 ID。
返回值
一个 Element 对象,描述与指定 ID 匹配的 DOM 元素对象,如果文档中未找到匹配元素,则为 null。
示例
HTML
<p id="para">Some text here</p>
<button>blue</button>
<button>red</button>
JavaScript
function changeColor(newColor) {
const elem = document.getElementById("para");
elem.style.color = newColor;
}
document.querySelectorAll("button").forEach((button) => {
button.addEventListener("click", (event) => {
changeColor(event.target.textContent.toLowerCase());
});
});
结果
用法说明
与其他一些元素查找方法(例如 Document.querySelector() 和 Document.querySelectorAll())不同,getElementById() 仅作为全局 document 对象的方法可用,而不能作为 DOM 中所有元素对象的方法可用。由于 ID 值在整个文档中必须是唯一的,因此不需要该函数的“本地”版本。
示例
<div id="parent-id">
<p>hello word1</p>
<p id="test1">hello word2</p>
<p>hello word3</p>
<p>hello word4</p>
</div>
const parentDOM = document.getElementById("parent-id");
const test1 = parentDOM.getElementById("test1");
如果没有给定 id 的元素,此函数返回 null。请注意,id 参数区分大小写,因此 document.getElementById("Main") 将返回 null 而不是元素 <div id="main">,因为在此方法的用途中,“M”和“m”是不同的。
getElementById() 不会搜索不在文档中的元素。在创建元素并为其分配 ID 时,必须使用 Node.insertBefore() 或类似方法将元素插入文档树中,然后才能使用 getElementById() 访问它。
const element = document.createElement("div");
element.id = "test";
const el = document.getElementById("test"); // el will be null!
在非 HTML 文档中,DOM 实现必须知道哪些属性是 ID 类型。名称为“id”的属性不是 ID 类型,除非在文档的 DTD 中如此定义。在 XHTML、XUL 和其他常见情况下,id 属性被定义为 ID 类型。不知道属性是否为 ID 类型的实现应该返回 null。
规范
| 规范 |
|---|
| DOM # ref-for-dom-nonelementparentnode-getelementbyid② |
浏览器兼容性
加载中…
另见
Document引用,用于获取文档中元素的引用的其他方法和属性。Document.querySelector(),用于通过查询(如'div.myclass')进行选择器选择。Document.evaluate()- 在 XML 文档中有一个通过xml:id进行选择的实用方法。