Element:getElementsByTagName() 方法
Element.getElementsByTagName() 方法返回一個即時的 HTMLCollection,其中包含具有指定 標籤名 的元素。
搜尋將查詢指定元素的**所有後代元素**,但不包括元素本身。返回的列表是即時的,這意味著它會自動更新 DOM 樹。因此,如果在呼叫之間 DOM 發生變化,則無需重複呼叫具有相同元素和引數的 Element.getElementsByTagName()。
在 HTML 文件中的 HTML 元素上呼叫時,getElementsByTagName 會將引數轉換為小寫後再進行搜尋。當嘗試匹配 HTML 文件中的駝峰式命名的 SVG 元素(例如 <linearGradient>)時,這會導致不期望的結果。因此,請改用 Element.getElementsByTagNameNS(),它會保留標籤名的原始大小寫。
Element.getElementsByTagName 與 Document.getElementsByTagName() 類似,不同之處在於它只搜尋指定元素的後代元素。
語法
js
getElementsByTagName(tagName)
引數
tagName-
要查詢的限定名稱。特殊字串
"*"代表所有元素。為了與 XHTML 相容,應使用小寫。
返回值
一個即時的 HTMLCollection,包含具有匹配標籤名的元素,並按照它們出現的順序排列。如果沒有找到元素,則 HTMLCollection 為空。
示例
js
// Check the status of each data cell in a table
const table = document.getElementById("forecast-table");
const cells = table.getElementsByTagName("td");
for (const cell of cells) {
const status = cell.getAttribute("data-status");
if (status === "open") {
// Grab the data
}
}
規範
| 規範 |
|---|
| DOM # dom-element-getelementsbytagname |
瀏覽器相容性
載入中…