Document:getElementsByTagName() 方法
Document 介面的 getElementsByTagName 方法返回一個動態的 HTMLCollection,其中包含指定標籤名的所有元素。
搜尋範圍包括整個文件,也包括根節點。返回的 HTMLCollection 是動態的,這意味著它會自動更新以與 DOM 樹保持同步,而無需再次呼叫 document.getElementsByTagName()。
語法
getElementsByTagName(name)
引數
name-
一個表示元素名稱的字串。特殊字串
*代表所有元素。
返回值
一個動態的 HTMLCollection,包含了按在樹中出現的順序排列的已找到的元素。
示例
在下面的示例中,getElementsByTagName() 從一個特定的父元素開始,並從該父元素開始在 DOM 中遞迴地自上而下搜尋,構建一個所有與標籤 name 引數匹配的後代元素的集合。這演示了 document.getElementsByTagName() 和功能上完全相同的 Element.getElementsByTagName(),後者從 DOM 樹中的特定元素開始搜尋。
點選按鈕會使用 getElementsByTagName() 來計算特定父元素(文件本身或兩個巢狀的 <div> 元素之一)的後代段落元素的數量。
<p>Some outer text</p>
<p>Some outer text</p>
<div id="div1">
<p>Some div1 text</p>
<p>Some div1 text</p>
<p>Some div1 text</p>
<div id="div2">
<p>Some div2 text</p>
<p>Some div2 text</p>
</div>
</div>
<p>Some outer text</p>
<p>Some outer text</p>
<button id="btn1">Show all p elements in document</button>
<br />
<button id="btn2">Show all p elements in div1 element</button>
<br />
<button id="btn3">Show all p elements in div2 element</button>
body {
border: solid green 3px;
}
#div1 {
border: solid blue 3px;
}
#div2 {
border: solid red 3px;
}
function getAllParaElems() {
const allParas = document.getElementsByTagName("p");
const num = allParas.length;
alert(`There are ${num} paragraph in this document`);
}
function div1ParaElems() {
const div1 = document.getElementById("div1");
const div1Paras = div1.getElementsByTagName("p");
const num = div1Paras.length;
alert(`There are ${num} paragraph in #div1`);
}
function div2ParaElems() {
const div2 = document.getElementById("div2");
const div2Paras = div2.getElementsByTagName("p");
const num = div2Paras.length;
alert(`There are ${num} paragraph in #div2`);
}
document.getElementById("btn1").addEventListener("click", getAllParaElems);
document.getElementById("btn2").addEventListener("click", div1ParaElems);
document.getElementById("btn3").addEventListener("click", div2ParaElems);
注意
當在 HTML 文件上呼叫時,getElementsByTagName() 會在繼續操作前將其引數轉換為小寫。當試圖在 HTML 文件的子樹中匹配駝峰式 SVG 元素時,這並不理想。在這種情況下,document.getElementsByTagNameNS() 就很有用。另請參閱 Firefox bug 499656。
document.getElementsByTagName() 與 Element.getElementsByTagName() 類似,只是其搜尋範圍涵蓋整個文件。
規範
| 規範 |
|---|
| DOM # dom-document-getelementsbytagname 的相關引用① |
瀏覽器相容性
載入中…
另見
Element.getElementsByTagName()document.getElementById():透過id返回對元素的引用document.getElementsByName():透過name返回對元素的引用document.querySelector():透過諸如'div.myclass'等查詢來實現強大的選擇器功能