文件: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進行選擇的實用方法。