Using getElementByTagName() method in TypeScript

Updated: February 14, 2024 By: Guest Contributor Post a comment

Introduction

TypeScript provides a strong typing system on top of JavaScript, making it easier to work with the structure of DOM elements. One of the common tasks when working with the DOM is selecting elements by their tag name. This is where the getElementsByTagName() method becomes incredibly useful.

TypeScript and getElementsByTagName()

The getElementsByTagName() method is a way to select elements from the DOM based on their tag name. This method returns a live HTMLCollection of all elements with the specified tag name, allowing for further manipulation or iteration over these elements. Since TypeScript is a superset of JavaScript, it inherits all its methods, including DOM manipulation methods like getElementsByTagName().

Basic Example

const paragraphs: HTMLCollectionOf<HTMLParagraphElement> = document.getElementsByTagName('p');
console.log(paragraphs.length); // This will output the number of <p> tags

In the example above, we are querying the DOM for all <p> tags and logging the number of elements found. Note the use of TypeScript’s type annotations to specify the variable type as HTMLCollectionOf<HTMLParagraphElement>.

Iterating over Elements

for (let i = 0; i < paragraphs.length; i++) {
    console.log(paragraphs[i].textContent);
}

This example demonstrates iterating over the HTMLCollection returned by getElementsByTagName() to log the text content of each paragraph. This iteration pattern allows for the concise manipulation or reading of selected DOM elements.

Filtering Elements by Class

const coloredTextElements: HTMLCollectionOf<HTMLElement> = document.getElementsByTagName('span');

Array.from(coloredTextElements).filter(el => el.classList.contains('colored')).forEach(el => console.log(el.style.color));

Here, we are selecting all <span> elements and then filtering those which have a class named ‘colored’. For each element that matches, we log its CSS color style. This example showcases advanced manipulation and conditional processing of DOM elements in a TypeScript context.

Responding to Events

document.addEventListener('DOMContentLoaded', () => {
    const buttons: HTMLCollectionOf<HTMLButtonElement> = document.getElementsByTagName('button');
    Array.from(buttons).forEach(button => button.onclick = () => alert('Button clicked'));
});

In this example, we add an event listener for the DOMContentLoaded event to ensure our script runs after the full document is parsed. We select all buttons and assign an onclick event listener that alerts ‘Button clicked’ when any button is clicked. This illustrates integrating getElementsByTagName() with event handling in TypeScript.

Conclusion

The getElementsByTagName() method is a powerful tool in the TypeScript developer’s toolkit, allowing for efficient DOM manipulation and interaction. By leveraging TypeScript’s strong typing, developers can ensure more robust, maintainable, and error-resistant code. Whether you are iterating over elements, filtering collections, or responding to user events, getElementsByTagName() provides a versatile method for working with HTML elements by their tag name.