Element.getElementsByTagName() - Web APIs 编辑

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.getElementsByTagName() with the same element and arguments repeatedly if the DOM changes in between calls.

When called on an HTML element in an HTML document, getElementsByTagName lower-cases the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS(), which preserves the capitalization of the tag name.

Element.getElementsByTagName is similar to Document.getElementsByTagName(), except that it only searches for elements that are descendants of the specified element.

Syntax

elements = element.getElementsByTagName(tagName)
  • elements is a live HTMLCollection of elements with a matching tag name, in the order they appear. If no elements are found, the HTMLCollection is empty.
  • element is the element from where the search starts. Only the element's descendants are included, not the element itself.
  • tagName is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used.

Example

// Check the status of each data cell in a table
const table = document.getElementById('forecast-table');
const cells = table.getElementsByTagName('td');

for (let cell of cells) {
  let status = cell.getAttribute('data-status');
  if (status === 'open') {
    // Grab the data
  }
}

Specifications

SpecificationStatusComment
DOM
The definition of 'Element.getElementsByTagName()' in that specification.
Living StandardChanged the return value from NodeList to HTMLCollection
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Element.getElementsByTagName()' in that specification.
ObsoleteNo change from Document Object Model (DOM) Level 2 Core Specification
Document Object Model (DOM) Level 2 Core Specification
The definition of 'Element.getElementsByTagName()' in that specification.
ObsoleteNo change from Document Object Model (DOM) Level 1 Specification
Document Object Model (DOM) Level 1 Specification
The definition of 'Element.getElementsByTagName()' in that specification.
ObsoleteInitial definition

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:68 次

字数:5147

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文