HTML DOM Element getElementsByTagName()
示例
更改列表中第一個 <li> 元素的 HTML 內容
const list = document.getElementsByTagName("UL")[0];
list.getElementsByTagName("li")[0].innerHTML = "牛奶";
自己動手試一試 »
"myDIV" 中 <p> 元素的數量
const element = document.getElementById("myDIV");
const nodes = element.getElementsByTagName("p");
let numb = nodes.length;
自己動手試一試 »
更改 "myDIV" 中第二個 <p> 元素的字型大小
const element = document.getElementById("myDIV");
element.getElementsByTagName("p")[1].style.fontSize = "24px";
自己動手試一試 »
更多示例見下文。
描述
getElementsByTagName()
方法返回具有給定標籤名的所有子元素的集合。
getElementsByTagName()
方法返回一個即時的 HTMLCollection。
HTMLCollection
HTMLCollection 是一個類陣列的 HTML 元素集合(列表)。
length 屬性 返回集合中元素的數量。
元素可以透過索引訪問(從 0 開始)。
HTMLCollection 是即時的。當文件更改時它會自動更新。
語法
元素.getElementsByTagName(標籤名)
引數
引數 | 描述 |
標籤名 | 必需。 元素的標籤名。 |
返回值
型別 | 描述 |
物件 | 一個 HTMLCollection 物件。 具有指定標籤名的元素集合。 元素按其在文件中出現的順序排序。 |
更多示例
更改 "myDIV" 中所有 <p> 元素的背景顏色
const div = document.getElementById("myDIV");
const nodes = x.getElementsByTagName("P");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "紅色";
}
自己動手試一試 »
更改 "myDIV" 中第四個元素(索引 3)的背景顏色
const div = document.getElementById("myDIV");
div.getElementsByTagName("*")[3].style.backgroundColor = "紅色";
自己動手試一試 »
使用 "*" 引數。
更改 "myDIV" 中所有元素的背景顏色
const div = document.getElementById("myDIV");
const nodes = div.getElementsByTagName("*");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "紅色";
}
自己動手試一試 »
瀏覽器支援
element.getElementsByTagName()
在所有瀏覽器中都受支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |