Skip to main content

getElementsByTagName in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the getElementsByTagName method in JavaScript to select and manipulate HTML elements by their tag name. We'll cover the basics of the method and provide sample code with explanations.

What is getElementsByTagName?

The getElementsByTagName method is a built-in JavaScript DOM method that allows you to select a collection of HTML elements by their tag name. The method returns a live HTMLCollection of all elements with the specified tag name, or an empty collection if no elements with the given tag name are found. It enables you to access multiple elements with the same tag name and perform various operations, such as modifying content or applying styles.

Sample Code: Using getElementsByTagName

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<h1>Welcome to My Web Page!</h1>
<p>This is an introductory paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

To use getElementsByTagName to select elements, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can select all p elements and change their text content:

<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<h1>Welcome to My Web Page!</h1>
<p>This is an introductory paragraph.</p>
<p>This is another paragraph.</p>

<script>
// Select all elements with the tag name "p"
var paragraphs = document.getElementsByTagName('p');

// Loop through the collection and change the text content of each element
for (var i = 0; i < paragraphs.length; i++) {
paragraphs[i].textContent = 'This paragraph has been updated.';
}
</script>
</body>
</html>

After running this code, the text content of all p elements will be updated to "This paragraph has been updated.".

Live Playground, Try it Yourself

Conclusion

The getElementsByTagName method is a powerful way to select and manipulate HTML elements by their tag name. By mastering this method, you can easily access and modify multiple elements with the same tag name in your HTML documents, allowing you to create dynamic and interactive web pages.