ZetCode

JavaScript getElementsByTagName

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 getElementsByTagName 方法。此方法对于 DOM 操作至关重要,它允许开发人员在特定上下文中按标签名称访问元素。

基本定义

getElementsByTagName 方法返回一个具有给定标签名称的元素的实时 HTMLCollection。它可以对任何元素或文档对象调用,以在该上下文中进行搜索。

getElementById 不同,此方法返回多个元素。该集合是实时的,这意味着当 DOM 发生更改时,它会自动更新。

基本 getElementsByTagName

此示例演示了如何访问文档中的所有段落元素。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic getElementsByTagName</title>
</head>
<body>

<p>First paragraph</p>
<p>Second paragraph</p>
<div>A div element</div>
<p>Third paragraph</p>

<script>
    const paragraphs = document.getElementsByTagName('p');
    console.log(paragraphs.length); // Outputs: 3
    console.log(paragraphs[1].textContent); // Outputs: Second paragraph
</script>

</body>
</html>

在此基本示例中,我们使用 getElementsByTagName 获取所有段落元素。该方法返回一个 HTMLCollection,我们可以像数组一样访问它。

该示例展示了如何检查找到的元素数量以及如何通过索引位置从集合中访问特定元素。

在特定元素内搜索

此示例展示了如何对特定元素而不是整个文档使用 getElementsByTagName

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Searching Within Element</title>
</head>
<body>

<div id="content">
    <p>First paragraph in content</p>
    <span>A span element</span>
    <p>Second paragraph in content</p>
</div>
<p>Paragraph outside content</p>

<script>
    const contentDiv = document.getElementById('content');
    const contentParagraphs = contentDiv.getElementsByTagName('p');
    
    console.log(contentParagraphs.length); // Outputs: 2
    contentParagraphs[0].style.color = 'red';
</script>

</body>
</html>

在这里,我们首先获取对特定 div 元素的引用,然后在该元素上使用 getElementsByTagName 来查找其中的段落。

这表明搜索范围可以限制在 DOM 树的特定部分,这比搜索整个文档更有效。

使用实时集合

此示例演示了 getElementsByTagName 返回的 HTMLCollection 的实时特性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Live Collection</title>
</head>
<body>

<ul id="list">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>
<button onclick="addItem()">Add Item</button>

<script>
    const listItems = document.getElementsByTagName('li');
    console.log(listItems.length); // Initially 2
    
    function addItem() {
        const newItem = document.createElement('li');
        newItem.textContent = 'New Item';
        document.getElementById('list').appendChild(newItem);
        console.log(listItems.length); // Increases each click
    }
</script>

</body>
</html>

此示例显示了当新元素添加到 DOM 时,集合如何自动更新。listItems 集合保持最新,无需重新查询。

集合的实时性在某些场景下可能很有用,也可能带来潜在问题,尤其是在大型 DOM 的性能方面。

遍历元素

此示例演示了遍历 getElementsByTagName 返回的元素的各种方法。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Iterating Elements</title>
</head>
<body>

<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>

<script>
    const items = document.getElementsByTagName('div');
    
    // Using a for loop
    for (let i = 0; i < items.length; i++) {
        items[i].style.color = 'blue';
    }
    
    // Using for...of (modern browsers)
    for (const item of items) {
        item.style.fontWeight = 'bold';
    }
    
    // Converting to array (for array methods)
    Array.from(items).forEach(item => {
        console.log(item.textContent);
    });
</script>

</body>
</html>

此示例展示了处理集合的三种不同方法:传统的 for 循环、for...of 循环和转换为数组。

每种方法都有其用途。数组转换特别适用于您想使用 forEachmapfilter 等数组方法时。

与其他 DOM 方法结合使用

此示例展示了如何将 getElementsByTagName 与其他 DOM 方法结合以进行更复杂的查询。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Combining Methods</title>
</head>
<body>

<div class="section">
    <h2>Section 1</h2>
    <p>Content 1</p>
</div>
<div class="section">
    <h2>Section 2</h2>
    <p>Content 2</p>
</div>

<script>
    // Get all sections
    const sections = document.getElementsByClassName('section');
    
    // For each section, get its h2 and p elements
    for (const section of sections) {
        const heading = section.getElementsByTagName('h2')[0];
        const paragraph = section.getElementsByTagName('p')[0];
        
        console.log(heading.textContent + ': ' + paragraph.textContent);
    }
</script>

</body>
</html>

在此示例中,我们首先获取所有类名为“section”的元素,然后对于每个 section,我们使用 getElementsByTagName 查找其 h2 和 p 元素。

这表明 DOM 方法可以组合起来创建更具体的查询,从而使您能够精确地定位需要使用的元素。

来源

MDN getElementsByTagName 文档

在本文中,我们展示了如何在 JavaScript 中使用 getElementsByTagName。当您需要按标签名称处理元素时,此方法是 DOM 操作的基础。

作者

我叫 Jan Bodnar,我是一名充满激情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS DOM 教程