getElementsByTagName Method
In this tutorial, we will learn about the getElementsByTagName method in JavaScript.
In JavaScript, the getElementsByTagName() method is used to get a collection of elements with the specified tag name from the document. It is a method of the document object that allows you to access and manipulate elements in the HTML document by their tag name.
Syntax
The syntax for the getElementsByTagName() method is as follows:
let elements = document.getElementsByTagName(tagName);Where:
- tagNameis a string that specifies the tag name of the elements you want to get.
- elementsis a collection of elements with the specified tag name.
Example
Suppose you have the following HTML document:
<!doctype html>
<html>
  <head>
    <title>Get Elements By Tag Name Example</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <script src="script.js"></script>
  </body>
</html>You can use the getElementsByTagName() method to get all <p> elements and change their content:
let elements = document.getElementsByTagName("p");
for (let i = 0; i < elements.length; i++) {
  elements[i].innerHTML = "This paragraph has been changed";
}This will change the content of all <p> elements to "This paragraph has been changed".
Conclusion
- The getElementsByTagName()method is used to get a collection of elements with the specified tag name from the document.
- It returns a collection of elements that match the specified tag name.
- You can use the getElementsByTagName()method to access and manipulate elements in the HTML document by their tag name.
- The collection returned by getElementsByTagName()is live, meaning that it will be updated automatically if the document changes.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on