How to get elements by tag name in JavaScript
Selecting HTML elements by their tag name is a fundamental DOM manipulation technique needed for dynamic web interactions.
As the creator of CoreUI with over 25 years of development experience, I’ve used tag-based selection extensively to build responsive UI components that adapt to different HTML structures.
The most efficient approach is using getElementsByTagName() when you need a live collection, or querySelectorAll() for modern selector-based selection.
Both methods are well-supported across all browsers and provide reliable element selection capabilities.
Use getElementsByTagName() to get all elements with a specific tag name as a live HTMLCollection.
const paragraphs = document.getElementsByTagName('p')
const firstParagraph = paragraphs[0]
const totalParagraphs = paragraphs.length
// Loop through all paragraphs
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.color = 'blue'
}
The getElementsByTagName() method returns a live HTMLCollection containing all elements with the specified tag name. This collection automatically updates when elements are added or removed from the DOM. You can access individual elements using array-like indexing and get the total count with the length property. The method searches the entire document or can be called on a specific parent element to limit the scope.
Best Practice Note:
This is the method we use in CoreUI components for reliable tag-based element selection.
For more complex selections, consider querySelectorAll('tagname') which returns a static NodeList and supports CSS selector syntax for advanced filtering.



