Cover Image for Javascript – document.getElementsByTagName()
225 views

Javascript – document.getElementsByTagName()

The JavaScriptdocument.getElementsByTagName() method is used to get a collection of all the elements in the document with a specific tag name. It returns an HTMLCollection object, which is an ordered collection of elements with the same tag name.

The getElementsByTagName() method takes a tag name as its parameter and returns an array-like object that contains all the elements in the document with the specified tag name.

The getElementsByTagName() method is called with the argument “p” to get all the <p> elements in the document. The returned HTMLCollection object is then logged to the console, which will output an array-like object containing all the <p> elements in the document. Note that the HTMLCollection object is not a true array and therefore cannot be manipulated using array methods, but it can be looped over using a for loop or converted to an array using Array.from().

Here is an example of how to use getElementsByTagName() method to get all the <p> elements in an HTML document:

HTML<span role="button" tabindex="0" data-code="<html> <head> <title>Example</title> </head> <body> <h1>My Heading</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> <script> const paragraphs = document.getElementsByTagName("p"); console.log(paragraphs); // Output: HTMLCollection[<p>, <p>] </script> </body>
<html>
<head>
  <title>Example</title>
</head>
<body>
  <h1>My Heading</h1>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <script>
    const paragraphs = document.getElementsByTagName("p");
    console.log(paragraphs); // Output: HTMLCollection[<p>, <p>]
  </script>
</body>
</html>

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS