HTML DOM getElementsByTagName() 方法用於獲取文檔中具有給定標簽名稱的所有元素的集合。它將所有給定元素作為 NodeList 對象返回。您可以使用索引號訪問返回對象中的任何元素。
返回的 HTMLcollection 與 DOM 樹保持同步,無需在刪除或添加一些元素後一次又一次地調用 getElementsByTagName() 方法。
用法
以下是 getElementsByTagName() 方法的語法 -
element.getElementsByTagName(tagname)
這裏,tagname 是一個強製參數值,指示我們想要獲取的子元素 tagname。
示例
讓我們看一個 getElementsByTagName() 方法的例子 -
<!DOCTYPE html>
<html>
<head>
<script>
function changePara() {
var p = document.getElementsByTagName("P");
p[0].innerHTML = "This text has been changed";
p[1].style.color = "red";
p[1].style.backgroundColor = "yellow";
}
</script>
</head>
<body>
<h1>getElementsByTagName() example</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<button onclick="changePara()">CHANGE</button>
</body>
</html>
輸出
這將產生以下輸出 -
單擊更改按鈕 -
在上麵的例子中 -
我們創建了兩個沒有關聯屬性的段落 -
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p> <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
然後我們創建了一個按鈕 CHANGE,它將在用戶單擊時執行 changePara() -
<button onclick="changePara()">CHANGE</button>
changePara() 方法在文檔對象上使用 getElementsByTagName() 方法將 <p> 元素作為 nodeListObject 獲取,並將其分配給變量 p。我們使用索引號更改第一段的文本並對第二段應用一些樣式 -
function changePara() {
var p = document.getElementsByClassName("PARA1");
p[0].innerHTML = "This text has been changed";
p[1].style.color = "red";
p[1].style.backgroundColor = "yellow";
}
相關用法
- HTML DOM getElementsByClassName()用法及代碼示例
- HTML DOM getElementById()用法及代碼示例
- HTML DOM getAttributeNode()用法及代碼示例
- HTML DOM getBoundingClientRect()用法及代碼示例
- HTML DOM getAttribute()用法及代碼示例
- HTML DOM getRangeAt()用法及代碼示例
- HTML DOM getNamedItem()用法及代碼示例
- HTML DOM Style overflowY屬性用法及代碼示例
- HTML DOM Document hidden屬性用法及代碼示例
- HTML DOM IFrame用法及代碼示例
- HTML DOM Textarea cols屬性用法及代碼示例
- HTML DOM Style pageBreakAfter屬性用法及代碼示例
- HTML DOM Base href屬性用法及代碼示例
- HTML DOM Pre用法及代碼示例
- HTML DOM Input Month用法及代碼示例
- HTML DOM Video canPlayType()用法及代碼示例
- HTML DOM Range deleteContents()用法及代碼示例
- HTML DOM console.dirxml()用法及代碼示例
- HTML DOM Style transition屬性用法及代碼示例
- HTML DOM Video volume屬性用法及代碼示例
注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM getElementsByTagName() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。