JavaScript – document.getElementsByTagName() method

The document.getElementsByTagName() method returns all the element of specified tag name.



tagname – Required. The tagname of the elements you want to get.

The parameter value “*” returns all elements in the document.

The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as an HTMLCollection object.

  • The HTMLCollection object represents a collection of nodes.
  • The nodes can be accessed by index numbers.
  • The index starts at 0.
  • length property of the HTMLCollection object is used to determine the number of elements with the specified tag name, then you can loop through all elements and extract the info you want.


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript - document.getElementsByTagName() method</title>

    <script type="text/javascript">
        function countpara() {
            var totalpara = document.getElementsByTagName("p");
            alert("total p tags are: " + totalpara.length);

    <p>This is a pragraph</p>
    <p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
    <p>Let's see the simple example</p>
    <button onclick="countpara()">count paragraph</button>

JavaScript – document.getElementsByTagName() method example output