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 |
浏览器兼容性
加载中…