In Javascript, the getElementsByTagName method is used to access HTML elements based on their tag name.
This method returns a live HTMLCollection, similar to an array, containing all elements with the specified tag name.
<script> var elements = document.getElementsByTagName('tag name'); </script>
tagName: It specifies the `Tag Name` of the HTML element we want to access either to fetch information or modify content.
Return value: If an element with the specified ID exists in the document (DOM), The `getElementsByTagName` function returns a reference to that element. Otherwise, it returns null.
Here, we have created HTML elements which we try to fetch using the document object method of `document.getElementsByTagName`.
<h1>This is a heading element</h1> <p>This is a paragraph element</p> <div>This is a div element</div>
Here, in Script we have added the Script tag and added `getElementsByTagName` function.
<script> // Accessing elements with the tag name 'p' var elements = document.getElementsByTagName('p'); // Looping through the collection and modifying each element for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = 'This content has been changed using JavaScript.'; } </script>
The `getElementsByTagName` method is used to obtain a reference of the HTML element with the `tag` name currently set to 'p'.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>getElementsByTagName Example</title> </head> <body> <h1>This is a heading element</h1> <p>This is a paragraph element</p> <div>This is a div element</div> <script> // Accessing elements with the tag name 'p' var elements = document.getElementsByTagName('p'); // Looping through the collection and modifying each element for (var i = 0; i < elements.length; i++) { elements[i].innerHTML = 'This content has been changed using JavaScript.'; } </script> </body> </html>
In the above example, we have created multiple elements such as `div`, `p` and `h1`.
In the Next Step, Inside the `Script` tag we try to access all elements whose tag name is `p`.
In the Next Lines, we are looping over the elements retrieved through the `getElementsByTagName` method and modifying the `content` of the elements.